blob: 3f00b788c302117aea286d62877a16d1fde9ddcc [file] [log] [blame]
Jeff Brown59abe7e2010-09-13 23:17:30 -07001/*
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 UTILS_LOOPER_H
18#define UTILS_LOOPER_H
19
20#include <utils/threads.h>
21#include <utils/RefBase.h>
22#include <utils/KeyedVector.h>
23
24#include <android/looper.h>
25
26/*
27 * Declare a concrete type for the NDK's looper forward declaration.
28 */
29struct ALooper {
30};
31
32namespace android {
33
34/**
35 * A polling loop that supports monitoring file descriptor events, optionally
36 * using callbacks. The implementation uses epoll() internally.
37 *
38 * A looper can be associated with a thread although there is no requirement that it must be.
39 */
40class Looper : public ALooper, public RefBase {
41protected:
42 virtual ~Looper();
43
44public:
45 /**
46 * Creates a looper.
47 *
48 * If allowNonCallbaks is true, the looper will allow file descriptors to be
49 * registered without associated callbacks. This assumes that the caller of
50 * pollOnce() is prepared to handle callback-less events itself.
51 */
52 Looper(bool allowNonCallbacks);
53
54 /**
55 * Returns whether this looper instance allows the registration of file descriptors
56 * using identifiers instead of callbacks.
57 */
58 bool getAllowNonCallbacks() const;
59
60 /**
61 * Waits for events to be available, with optional timeout in milliseconds.
62 * Invokes callbacks for all file descriptors on which an event occurred.
63 *
64 * If the timeout is zero, returns immediately without blocking.
65 * If the timeout is negative, waits indefinitely until an event appears.
66 *
67 * Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before
68 * the timeout expired and no callbacks were invoked and no other file
69 * descriptors were ready.
70 *
71 * Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked.
72 *
73 * Returns ALOOPER_POLL_TIMEOUT if there was no data before the given
74 * timeout expired.
75 *
76 * Returns ALOOPER_POLL_ERROR if an error occurred.
77 *
78 * Returns a value >= 0 containing an identifier if its file descriptor has data
79 * and it has no callback function (requiring the caller here to handle it).
80 * In this (and only this) case outFd, outEvents and outData will contain the poll
81 * events and data associated with the fd, otherwise they will be set to NULL.
82 *
83 * This method does not return until it has finished invoking the appropriate callbacks
84 * for all file descriptors that were signalled.
85 */
Jeff Brownb0619e82010-09-16 18:28:12 -070086 int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
87 inline int pollOnce(int timeoutMillis) {
88 return pollOnce(timeoutMillis, NULL, NULL, NULL);
89 }
Jeff Brown59abe7e2010-09-13 23:17:30 -070090
91 /**
92 * Like pollOnce(), but performs all pending callbacks until all
93 * data has been consumed or a file descriptor is available with no callback.
94 * This function will never return ALOOPER_POLL_CALLBACK.
95 */
Jeff Brownb0619e82010-09-16 18:28:12 -070096 int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
97 inline int pollAll(int timeoutMillis) {
98 return pollAll(timeoutMillis, NULL, NULL, NULL);
99 }
Jeff Brown59abe7e2010-09-13 23:17:30 -0700100
101 /**
102 * Wakes the poll asynchronously.
103 *
104 * This method can be called on any thread.
105 * This method returns immediately.
106 */
107 void wake();
108
109 /**
110 * Adds a new file descriptor to be polled by the looper.
111 * If the same file descriptor was previously added, it is replaced.
112 *
113 * "fd" is the file descriptor to be added.
114 * "ident" is an identifier for this event, which is returned from ALooper_pollOnce().
115 * The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
116 * "events" are the poll events to wake up on. Typically this is ALOOPER_EVENT_INPUT.
117 * "callback" is the function to call when there is an event on the file descriptor.
118 * "data" is a private data pointer to supply to the callback.
119 *
120 * There are two main uses of this function:
121 *
122 * (1) If "callback" is non-NULL, then this function will be called when there is
123 * data on the file descriptor. It should execute any events it has pending,
124 * appropriately reading from the file descriptor. The 'ident' is ignored in this case.
125 *
126 * (2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce
127 * when its file descriptor has data available, requiring the caller to take
128 * care of processing it.
129 *
130 * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
131 *
132 * This method can be called on any thread.
133 * This method may block briefly if it needs to wake the poll.
134 */
Jeff Brownb0619e82010-09-16 18:28:12 -0700135 int addFd(int fd, int ident, int events, ALooper_callbackFunc callback, void* data);
Jeff Brown59abe7e2010-09-13 23:17:30 -0700136
137 /**
138 * Removes a previously added file descriptor from the looper.
139 *
140 * When this method returns, it is safe to close the file descriptor since the looper
141 * will no longer have a reference to it. However, it is possible for the callback to
142 * already be running or for it to run one last time if the file descriptor was already
143 * signalled. Calling code is responsible for ensuring that this case is safely handled.
144 * For example, if the callback takes care of removing itself during its own execution either
145 * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
146 * again at any later time unless registered anew.
147 *
148 * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
149 *
150 * This method can be called on any thread.
151 * This method may block briefly if it needs to wake the poll.
152 */
153 int removeFd(int fd);
154
155 /**
156 * Prepares a looper associated with the calling thread, and returns it.
157 * If the thread already has a looper, it is returned. Otherwise, a new
158 * one is created, associated with the thread, and returned.
159 *
160 * The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0.
161 */
162 static sp<Looper> prepare(int opts);
163
164 /**
165 * Sets the given looper to be associated with the calling thread.
166 * If another looper is already associated with the thread, it is replaced.
167 *
168 * If "looper" is NULL, removes the currently associated looper.
169 */
170 static void setForThread(const sp<Looper>& looper);
171
172 /**
173 * Returns the looper associated with the calling thread, or NULL if
174 * there is not one.
175 */
176 static sp<Looper> getForThread();
177
178private:
179 struct Request {
180 int fd;
181 int ident;
182 ALooper_callbackFunc callback;
183 void* data;
184 };
185
186 struct Response {
187 int events;
188 Request request;
189 };
190
191 const bool mAllowNonCallbacks; // immutable
192
193 int mEpollFd; // immutable
194 int mWakeReadPipeFd; // immutable
195 int mWakeWritePipeFd; // immutable
196
197 // Locked list of file descriptor monitoring requests.
198 Mutex mLock;
199 KeyedVector<int, Request> mRequests;
200
201 // This state is only used privately by pollOnce and does not require a lock since
202 // it runs on a single thread.
203 Vector<Response> mResponses;
204 size_t mResponseIndex;
205
206 int pollInner(int timeoutMillis);
207
Jeff Brown61a25b22010-09-21 15:11:18 -0700208 static void initTLSKey();
Jeff Brown59abe7e2010-09-13 23:17:30 -0700209 static void threadDestructor(void *st);
210};
211
212} // namespace android
213
214#endif // UTILS_LOOPER_H