1 /*
2  * Copyright (C) 2008 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 #include <stdint.h>
18 #include <errno.h>
19 #include <poll.h>
20 #include <string.h>
21 #include <unistd.h>
22 
23 #include <sys/cdefs.h>
24 #include <sys/types.h>
25 
26 #include <linux/input.h>
27 
28 #include <cutils/log.h>
29 
30 #include "InputEventReader.h"
31 
32 /*****************************************************************************/
33 
34 struct input_event;
35 
InputEventCircularReader(size_t numEvents)36 InputEventCircularReader::InputEventCircularReader(size_t numEvents)
37     : mBuffer(new input_event[numEvents * 2]),
38       mBufferEnd(mBuffer + numEvents),
39       mHead(mBuffer),
40       mCurr(mBuffer),
41       mFreeSpace(numEvents)
42 {
43 }
44 
~InputEventCircularReader()45 InputEventCircularReader::~InputEventCircularReader()
46 {
47     delete [] mBuffer;
48 }
49 
fill(int fd)50 ssize_t InputEventCircularReader::fill(int fd)
51 {
52     size_t numEventsRead = 0;
53     if (mFreeSpace) {
54         const ssize_t nread = read(fd, mHead, mFreeSpace * sizeof(input_event));
55         if (nread<0 || nread % sizeof(input_event)) {
56             // we got a partial event!!
57             return nread<0 ? -errno : -EINVAL;
58         }
59 
60         numEventsRead = nread / sizeof(input_event);
61         if (numEventsRead) {
62             mHead += numEventsRead;
63             mFreeSpace -= numEventsRead;
64             if (mHead > mBufferEnd) {
65                 size_t s = mHead - mBufferEnd;
66                 memcpy(mBuffer, mBufferEnd, s * sizeof(input_event));
67                 mHead = mBuffer + s;
68             }
69         }
70     }
71 
72     return numEventsRead;
73 }
74 
readEvent(input_event const ** events)75 ssize_t InputEventCircularReader::readEvent(input_event const** events)
76 {
77     *events = mCurr;
78     ssize_t available = (mBufferEnd - mBuffer) - mFreeSpace;
79     return available ? 1 : 0;
80 }
81 
next()82 void InputEventCircularReader::next()
83 {
84     mCurr++;
85     mFreeSpace++;
86     if (mCurr >= mBufferEnd) {
87         mCurr = mBuffer;
88     }
89 }
90