Home | History | Annotate | Download | only in ui
      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 _UI_INPUT_TRANSPORT_H
     18 #define _UI_INPUT_TRANSPORT_H
     19 
     20 /**
     21  * Native input transport.
     22  *
     23  * Uses anonymous shared memory as a whiteboard for sending input events from an
     24  * InputPublisher to an InputConsumer and ensuring appropriate synchronization.
     25  * One interesting feature is that published events can be updated in place as long as they
     26  * have not yet been consumed.
     27  *
     28  * The InputPublisher and InputConsumer only take care of transferring event data
     29  * over an InputChannel and sending synchronization signals.  The InputDispatcher and InputQueue
     30  * build on these abstractions to add multiplexing and queueing.
     31  */
     32 
     33 #include <semaphore.h>
     34 #include <ui/Input.h>
     35 #include <utils/Errors.h>
     36 #include <utils/Timers.h>
     37 #include <utils/RefBase.h>
     38 #include <utils/String8.h>
     39 
     40 namespace android {
     41 
     42 /*
     43  * An input channel consists of a shared memory buffer and a pair of pipes
     44  * used to send input messages from an InputPublisher to an InputConsumer
     45  * across processes.  Each channel has a descriptive name for debugging purposes.
     46  *
     47  * Each endpoint has its own InputChannel object that specifies its own file descriptors.
     48  *
     49  * The input channel is closed when all references to it are released.
     50  */
     51 class InputChannel : public RefBase {
     52 protected:
     53     virtual ~InputChannel();
     54 
     55 public:
     56     InputChannel(const String8& name, int32_t ashmemFd, int32_t receivePipeFd,
     57             int32_t sendPipeFd);
     58 
     59     /* Creates a pair of input channels and their underlying shared memory buffers
     60      * and pipes.
     61      *
     62      * Returns OK on success.
     63      */
     64     static status_t openInputChannelPair(const String8& name,
     65             sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
     66 
     67     inline String8 getName() const { return mName; }
     68     inline int32_t getAshmemFd() const { return mAshmemFd; }
     69     inline int32_t getReceivePipeFd() const { return mReceivePipeFd; }
     70     inline int32_t getSendPipeFd() const { return mSendPipeFd; }
     71 
     72     /* Sends a signal to the other endpoint.
     73      *
     74      * Returns OK on success.
     75      * Returns DEAD_OBJECT if the channel's peer has been closed.
     76      * Other errors probably indicate that the channel is broken.
     77      */
     78     status_t sendSignal(char signal);
     79 
     80     /* Receives a signal send by the other endpoint.
     81      * (Should only call this after poll() indicates that the receivePipeFd has available input.)
     82      *
     83      * Returns OK on success.
     84      * Returns WOULD_BLOCK if there is no signal present.
     85      * Returns DEAD_OBJECT if the channel's peer has been closed.
     86      * Other errors probably indicate that the channel is broken.
     87      */
     88     status_t receiveSignal(char* outSignal);
     89 
     90 private:
     91     String8 mName;
     92     int32_t mAshmemFd;
     93     int32_t mReceivePipeFd;
     94     int32_t mSendPipeFd;
     95 };
     96 
     97 /*
     98  * Private intermediate representation of input events as messages written into an
     99  * ashmem buffer.
    100  */
    101 struct InputMessage {
    102     /* Semaphore count is set to 1 when the message is published.
    103      * It becomes 0 transiently while the publisher updates the message.
    104      * It becomes 0 permanently when the consumer consumes the message.
    105      */
    106     sem_t semaphore;
    107 
    108     /* Initialized to false by the publisher.
    109      * Set to true by the consumer when it consumes the message.
    110      */
    111     bool consumed;
    112 
    113     int32_t type;
    114 
    115     struct SampleData {
    116         nsecs_t eventTime;
    117         PointerCoords coords[0]; // variable length
    118     };
    119 
    120     int32_t deviceId;
    121     int32_t source;
    122 
    123     union {
    124         struct {
    125             int32_t action;
    126             int32_t flags;
    127             int32_t keyCode;
    128             int32_t scanCode;
    129             int32_t metaState;
    130             int32_t repeatCount;
    131             nsecs_t downTime;
    132             nsecs_t eventTime;
    133         } key;
    134 
    135         struct {
    136             int32_t action;
    137             int32_t flags;
    138             int32_t metaState;
    139             int32_t edgeFlags;
    140             nsecs_t downTime;
    141             float xOffset;
    142             float yOffset;
    143             float xPrecision;
    144             float yPrecision;
    145             size_t pointerCount;
    146             int32_t pointerIds[MAX_POINTERS];
    147             size_t sampleCount;
    148             SampleData sampleData[0]; // variable length
    149         } motion;
    150     };
    151 
    152     /* Gets the number of bytes to add to step to the next SampleData object in a motion
    153      * event message for a given number of pointers.
    154      */
    155     static inline size_t sampleDataStride(size_t pointerCount) {
    156         return sizeof(InputMessage::SampleData) + pointerCount * sizeof(PointerCoords);
    157     }
    158 
    159     /* Adds the SampleData stride to the given pointer. */
    160     static inline SampleData* sampleDataPtrIncrement(SampleData* ptr, size_t stride) {
    161         return reinterpret_cast<InputMessage::SampleData*>(reinterpret_cast<char*>(ptr) + stride);
    162     }
    163 };
    164 
    165 /*
    166  * Publishes input events to an anonymous shared memory buffer.
    167  * Uses atomic operations to coordinate shared access with a single concurrent consumer.
    168  */
    169 class InputPublisher {
    170 public:
    171     /* Creates a publisher associated with an input channel. */
    172     explicit InputPublisher(const sp<InputChannel>& channel);
    173 
    174     /* Destroys the publisher and releases its input channel. */
    175     ~InputPublisher();
    176 
    177     /* Gets the underlying input channel. */
    178     inline sp<InputChannel> getChannel() { return mChannel; }
    179 
    180     /* Prepares the publisher for use.  Must be called before it is used.
    181      * Returns OK on success.
    182      *
    183      * This method implicitly calls reset(). */
    184     status_t initialize();
    185 
    186     /* Resets the publisher to its initial state and unpins its ashmem buffer.
    187      * Returns OK on success.
    188      *
    189      * Should be called after an event has been consumed to release resources used by the
    190      * publisher until the next event is ready to be published.
    191      */
    192     status_t reset();
    193 
    194     /* Publishes a key event to the ashmem buffer.
    195      *
    196      * Returns OK on success.
    197      * Returns INVALID_OPERATION if the publisher has not been reset.
    198      */
    199     status_t publishKeyEvent(
    200             int32_t deviceId,
    201             int32_t source,
    202             int32_t action,
    203             int32_t flags,
    204             int32_t keyCode,
    205             int32_t scanCode,
    206             int32_t metaState,
    207             int32_t repeatCount,
    208             nsecs_t downTime,
    209             nsecs_t eventTime);
    210 
    211     /* Publishes a motion event to the ashmem buffer.
    212      *
    213      * Returns OK on success.
    214      * Returns INVALID_OPERATION if the publisher has not been reset.
    215      * Returns BAD_VALUE if pointerCount is less than 1 or greater than MAX_POINTERS.
    216      */
    217     status_t publishMotionEvent(
    218             int32_t deviceId,
    219             int32_t source,
    220             int32_t action,
    221             int32_t flags,
    222             int32_t edgeFlags,
    223             int32_t metaState,
    224             float xOffset,
    225             float yOffset,
    226             float xPrecision,
    227             float yPrecision,
    228             nsecs_t downTime,
    229             nsecs_t eventTime,
    230             size_t pointerCount,
    231             const int32_t* pointerIds,
    232             const PointerCoords* pointerCoords);
    233 
    234     /* Appends a motion sample to a motion event unless already consumed.
    235      *
    236      * Returns OK on success.
    237      * Returns INVALID_OPERATION if the current event is not a AMOTION_EVENT_ACTION_MOVE event.
    238      * Returns FAILED_TRANSACTION if the current event has already been consumed.
    239      * Returns NO_MEMORY if the buffer is full and no additional samples can be added.
    240      */
    241     status_t appendMotionSample(
    242             nsecs_t eventTime,
    243             const PointerCoords* pointerCoords);
    244 
    245     /* Sends a dispatch signal to the consumer to inform it that a new message is available.
    246      *
    247      * Returns OK on success.
    248      * Errors probably indicate that the channel is broken.
    249      */
    250     status_t sendDispatchSignal();
    251 
    252     /* Receives the finished signal from the consumer in reply to the original dispatch signal.
    253      *
    254      * Returns OK on success.
    255      * Returns WOULD_BLOCK if there is no signal present.
    256      * Other errors probably indicate that the channel is broken.
    257      */
    258     status_t receiveFinishedSignal();
    259 
    260 private:
    261     sp<InputChannel> mChannel;
    262 
    263     size_t mAshmemSize;
    264     InputMessage* mSharedMessage;
    265     bool mPinned;
    266     bool mSemaphoreInitialized;
    267     bool mWasDispatched;
    268 
    269     size_t mMotionEventPointerCount;
    270     InputMessage::SampleData* mMotionEventSampleDataTail;
    271     size_t mMotionEventSampleDataStride;
    272 
    273     status_t publishInputEvent(
    274             int32_t type,
    275             int32_t deviceId,
    276             int32_t source);
    277 };
    278 
    279 /*
    280  * Consumes input events from an anonymous shared memory buffer.
    281  * Uses atomic operations to coordinate shared access with a single concurrent publisher.
    282  */
    283 class InputConsumer {
    284 public:
    285     /* Creates a consumer associated with an input channel. */
    286     explicit InputConsumer(const sp<InputChannel>& channel);
    287 
    288     /* Destroys the consumer and releases its input channel. */
    289     ~InputConsumer();
    290 
    291     /* Gets the underlying input channel. */
    292     inline sp<InputChannel> getChannel() { return mChannel; }
    293 
    294     /* Prepares the consumer for use.  Must be called before it is used. */
    295     status_t initialize();
    296 
    297     /* Consumes the input event in the buffer and copies its contents into
    298      * an InputEvent object created using the specified factory.
    299      * This operation will block if the publisher is updating the event.
    300      *
    301      * Returns OK on success.
    302      * Returns INVALID_OPERATION if there is no currently published event.
    303      * Returns NO_MEMORY if the event could not be created.
    304      */
    305     status_t consume(InputEventFactoryInterface* factory, InputEvent** outEvent);
    306 
    307     /* Sends a finished signal to the publisher to inform it that the current message is
    308      * finished processing.
    309      *
    310      * Returns OK on success.
    311      * Errors probably indicate that the channel is broken.
    312      */
    313     status_t sendFinishedSignal();
    314 
    315     /* Receives the dispatched signal from the publisher.
    316      *
    317      * Returns OK on success.
    318      * Returns WOULD_BLOCK if there is no signal present.
    319      * Other errors probably indicate that the channel is broken.
    320      */
    321     status_t receiveDispatchSignal();
    322 
    323 private:
    324     sp<InputChannel> mChannel;
    325 
    326     size_t mAshmemSize;
    327     InputMessage* mSharedMessage;
    328 
    329     void populateKeyEvent(KeyEvent* keyEvent) const;
    330     void populateMotionEvent(MotionEvent* motionEvent) const;
    331 };
    332 
    333 } // namespace android
    334 
    335 #endif // _UI_INPUT_TRANSPORT_H
    336