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