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