blob: 84e3864a6733d00e2132b6f60f8de1e0055b4983 [file] [log] [blame]
Jeff Brown7901eb22010-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>
Jeff Brown8d15c742010-10-05 15:35:37 -070023#include <utils/Timers.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070024
25#include <android/looper.h>
26
Jeff Brown8d15c742010-10-05 15:35:37 -070027#include <sys/epoll.h>
Jeff Brown8d15c742010-10-05 15:35:37 -070028
Jeff Brown7901eb22010-09-13 23:17:30 -070029/*
30 * Declare a concrete type for the NDK's looper forward declaration.
31 */
32struct ALooper {
33};
34
35namespace android {
36
37/**
Jeff Brown3e2e38b2011-03-02 14:41:58 -080038 * A message that can be posted to a Looper.
39 */
40struct Message {
41 Message() : what(0) { }
42 Message(int what) : what(what) { }
43
44 /* The message type. (interpretation is left up to the handler) */
45 int what;
46};
47
48
49/**
50 * Interface for a Looper message handler.
51 *
52 * The Looper holds a strong reference to the message handler whenever it has
53 * a message to deliver to it. Make sure to call Looper::removeMessages
54 * to remove any pending messages destined for the handler so that the handler
55 * can be destroyed.
56 */
57class MessageHandler : public virtual RefBase {
58protected:
59 virtual ~MessageHandler() { }
60
61public:
62 /**
63 * Handles a message.
64 */
65 virtual void handleMessage(const Message& message) = 0;
66};
67
68
69/**
70 * A simple proxy that holds a weak reference to a message handler.
71 */
72class WeakMessageHandler : public MessageHandler {
73public:
74 WeakMessageHandler(const wp<MessageHandler>& handler);
75 virtual void handleMessage(const Message& message);
76
77private:
78 wp<MessageHandler> mHandler;
79};
80
81
82/**
Jeff Brown7901eb22010-09-13 23:17:30 -070083 * A polling loop that supports monitoring file descriptor events, optionally
84 * using callbacks. The implementation uses epoll() internally.
85 *
86 * A looper can be associated with a thread although there is no requirement that it must be.
87 */
88class Looper : public ALooper, public RefBase {
89protected:
90 virtual ~Looper();
91
92public:
93 /**
94 * Creates a looper.
95 *
96 * If allowNonCallbaks is true, the looper will allow file descriptors to be
97 * registered without associated callbacks. This assumes that the caller of
98 * pollOnce() is prepared to handle callback-less events itself.
99 */
100 Looper(bool allowNonCallbacks);
101
102 /**
103 * Returns whether this looper instance allows the registration of file descriptors
104 * using identifiers instead of callbacks.
105 */
106 bool getAllowNonCallbacks() const;
107
108 /**
109 * Waits for events to be available, with optional timeout in milliseconds.
110 * Invokes callbacks for all file descriptors on which an event occurred.
111 *
112 * If the timeout is zero, returns immediately without blocking.
113 * If the timeout is negative, waits indefinitely until an event appears.
114 *
115 * Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before
116 * the timeout expired and no callbacks were invoked and no other file
117 * descriptors were ready.
118 *
119 * Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked.
120 *
121 * Returns ALOOPER_POLL_TIMEOUT if there was no data before the given
122 * timeout expired.
123 *
124 * Returns ALOOPER_POLL_ERROR if an error occurred.
125 *
126 * Returns a value >= 0 containing an identifier if its file descriptor has data
127 * and it has no callback function (requiring the caller here to handle it).
128 * In this (and only this) case outFd, outEvents and outData will contain the poll
129 * events and data associated with the fd, otherwise they will be set to NULL.
130 *
131 * This method does not return until it has finished invoking the appropriate callbacks
132 * for all file descriptors that were signalled.
133 */
Jeff Brown905682a2010-09-16 18:28:12 -0700134 int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
135 inline int pollOnce(int timeoutMillis) {
136 return pollOnce(timeoutMillis, NULL, NULL, NULL);
137 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700138
139 /**
140 * Like pollOnce(), but performs all pending callbacks until all
141 * data has been consumed or a file descriptor is available with no callback.
142 * This function will never return ALOOPER_POLL_CALLBACK.
143 */
Jeff Brown905682a2010-09-16 18:28:12 -0700144 int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
145 inline int pollAll(int timeoutMillis) {
146 return pollAll(timeoutMillis, NULL, NULL, NULL);
147 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700148
149 /**
150 * Wakes the poll asynchronously.
151 *
152 * This method can be called on any thread.
153 * This method returns immediately.
154 */
155 void wake();
156
157 /**
158 * Adds a new file descriptor to be polled by the looper.
159 * If the same file descriptor was previously added, it is replaced.
160 *
161 * "fd" is the file descriptor to be added.
162 * "ident" is an identifier for this event, which is returned from ALooper_pollOnce().
163 * The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
164 * "events" are the poll events to wake up on. Typically this is ALOOPER_EVENT_INPUT.
165 * "callback" is the function to call when there is an event on the file descriptor.
166 * "data" is a private data pointer to supply to the callback.
167 *
168 * There are two main uses of this function:
169 *
170 * (1) If "callback" is non-NULL, then this function will be called when there is
171 * data on the file descriptor. It should execute any events it has pending,
172 * appropriately reading from the file descriptor. The 'ident' is ignored in this case.
173 *
174 * (2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce
175 * when its file descriptor has data available, requiring the caller to take
176 * care of processing it.
177 *
178 * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
179 *
180 * This method can be called on any thread.
181 * This method may block briefly if it needs to wake the poll.
182 */
Jeff Brown905682a2010-09-16 18:28:12 -0700183 int addFd(int fd, int ident, int events, ALooper_callbackFunc callback, void* data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700184
185 /**
186 * Removes a previously added file descriptor from the looper.
187 *
188 * When this method returns, it is safe to close the file descriptor since the looper
189 * will no longer have a reference to it. However, it is possible for the callback to
190 * already be running or for it to run one last time if the file descriptor was already
191 * signalled. Calling code is responsible for ensuring that this case is safely handled.
192 * For example, if the callback takes care of removing itself during its own execution either
193 * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
194 * again at any later time unless registered anew.
195 *
196 * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
197 *
198 * This method can be called on any thread.
199 * This method may block briefly if it needs to wake the poll.
200 */
201 int removeFd(int fd);
202
203 /**
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800204 * Enqueues a message to be processed by the specified handler.
205 *
206 * The handler must not be null.
207 * This method can be called on any thread.
208 */
209 void sendMessage(const sp<MessageHandler>& handler, const Message& message);
210
211 /**
212 * Enqueues a message to be processed by the specified handler after all pending messages
213 * after the specified delay.
214 *
215 * The time delay is specified in uptime nanoseconds.
216 * The handler must not be null.
217 * This method can be called on any thread.
218 */
219 void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
220 const Message& message);
221
222 /**
223 * Enqueues a message to be processed by the specified handler after all pending messages
224 * at the specified time.
225 *
226 * The time is specified in uptime nanoseconds.
227 * The handler must not be null.
228 * This method can be called on any thread.
229 */
230 void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
231 const Message& message);
232
233 /**
234 * Removes all messages for the specified handler from the queue.
235 *
236 * The handler must not be null.
237 * This method can be called on any thread.
238 */
239 void removeMessages(const sp<MessageHandler>& handler);
240
241 /**
242 * Removes all messages of a particular type for the specified handler from the queue.
243 *
244 * The handler must not be null.
245 * This method can be called on any thread.
246 */
247 void removeMessages(const sp<MessageHandler>& handler, int what);
248
249 /**
Jeff Brown7901eb22010-09-13 23:17:30 -0700250 * Prepares a looper associated with the calling thread, and returns it.
251 * If the thread already has a looper, it is returned. Otherwise, a new
252 * one is created, associated with the thread, and returned.
253 *
254 * The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0.
255 */
256 static sp<Looper> prepare(int opts);
257
258 /**
259 * Sets the given looper to be associated with the calling thread.
260 * If another looper is already associated with the thread, it is replaced.
261 *
262 * If "looper" is NULL, removes the currently associated looper.
263 */
264 static void setForThread(const sp<Looper>& looper);
265
266 /**
267 * Returns the looper associated with the calling thread, or NULL if
268 * there is not one.
269 */
270 static sp<Looper> getForThread();
271
272private:
273 struct Request {
274 int fd;
275 int ident;
276 ALooper_callbackFunc callback;
277 void* data;
278 };
279
280 struct Response {
281 int events;
282 Request request;
283 };
284
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800285 struct MessageEnvelope {
286 MessageEnvelope() : uptime(0) { }
287
288 MessageEnvelope(nsecs_t uptime, const sp<MessageHandler> handler,
289 const Message& message) : uptime(uptime), handler(handler), message(message) {
290 }
291
292 nsecs_t uptime;
293 sp<MessageHandler> handler;
294 Message message;
295 };
296
Jeff Brown7901eb22010-09-13 23:17:30 -0700297 const bool mAllowNonCallbacks; // immutable
298
Jeff Brown7901eb22010-09-13 23:17:30 -0700299 int mWakeReadPipeFd; // immutable
300 int mWakeWritePipeFd; // immutable
Jeff Brown8d15c742010-10-05 15:35:37 -0700301 Mutex mLock;
302
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800303 Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
304 bool mSendingMessage; // guarded by mLock
305
Jeff Brown8d15c742010-10-05 15:35:37 -0700306 int mEpollFd; // immutable
Jeff Brown7901eb22010-09-13 23:17:30 -0700307
308 // Locked list of file descriptor monitoring requests.
Jeff Brown8d15c742010-10-05 15:35:37 -0700309 KeyedVector<int, Request> mRequests; // guarded by mLock
Jeff Brown8d15c742010-10-05 15:35:37 -0700310
Jeff Brown7901eb22010-09-13 23:17:30 -0700311 // This state is only used privately by pollOnce and does not require a lock since
312 // it runs on a single thread.
313 Vector<Response> mResponses;
314 size_t mResponseIndex;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800315 nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
Jeff Brown7901eb22010-09-13 23:17:30 -0700316
317 int pollInner(int timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700318 void awoken();
319 void pushResponse(int events, const Request& request);
Jeff Brown7901eb22010-09-13 23:17:30 -0700320
Jeff Brownd1805182010-09-21 15:11:18 -0700321 static void initTLSKey();
Jeff Brown7901eb22010-09-13 23:17:30 -0700322 static void threadDestructor(void *st);
323};
324
325} // namespace android
326
327#endif // UTILS_LOOPER_H