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