blob: 92e4b0ae9b31cfe7810351f7cdcf909380860b1c [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>
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 */
86 int pollOnce(int timeoutMillis,
87 int* outFd = NULL, int* outEvents = NULL, void** outData = NULL);
88
89 /**
90 * Like pollOnce(), but performs all pending callbacks until all
91 * data has been consumed or a file descriptor is available with no callback.
92 * This function will never return ALOOPER_POLL_CALLBACK.
93 */
94 int pollAll(int timeoutMillis,
95 int* outFd = NULL, int* outEvents = NULL, void** outData = NULL);
96
97 /**
98 * Wakes the poll asynchronously.
99 *
100 * This method can be called on any thread.
101 * This method returns immediately.
102 */
103 void wake();
104
105 /**
106 * Adds a new file descriptor to be polled by the looper.
107 * If the same file descriptor was previously added, it is replaced.
108 *
109 * "fd" is the file descriptor to be added.
110 * "ident" is an identifier for this event, which is returned from ALooper_pollOnce().
111 * The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
112 * "events" are the poll events to wake up on. Typically this is ALOOPER_EVENT_INPUT.
113 * "callback" is the function to call when there is an event on the file descriptor.
114 * "data" is a private data pointer to supply to the callback.
115 *
116 * There are two main uses of this function:
117 *
118 * (1) If "callback" is non-NULL, then this function will be called when there is
119 * data on the file descriptor. It should execute any events it has pending,
120 * appropriately reading from the file descriptor. The 'ident' is ignored in this case.
121 *
122 * (2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce
123 * when its file descriptor has data available, requiring the caller to take
124 * care of processing it.
125 *
126 * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
127 *
128 * This method can be called on any thread.
129 * This method may block briefly if it needs to wake the poll.
130 */
131 int addFd(int fd, int ident,
132 int events, ALooper_callbackFunc callback, void* data = NULL);
133
134 /**
135 * Removes a previously added file descriptor from the looper.
136 *
137 * When this method returns, it is safe to close the file descriptor since the looper
138 * will no longer have a reference to it. However, it is possible for the callback to
139 * already be running or for it to run one last time if the file descriptor was already
140 * signalled. Calling code is responsible for ensuring that this case is safely handled.
141 * For example, if the callback takes care of removing itself during its own execution either
142 * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
143 * again at any later time unless registered anew.
144 *
145 * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
146 *
147 * This method can be called on any thread.
148 * This method may block briefly if it needs to wake the poll.
149 */
150 int removeFd(int fd);
151
152 /**
153 * Prepares a looper associated with the calling thread, and returns it.
154 * If the thread already has a looper, it is returned. Otherwise, a new
155 * one is created, associated with the thread, and returned.
156 *
157 * The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0.
158 */
159 static sp<Looper> prepare(int opts);
160
161 /**
162 * Sets the given looper to be associated with the calling thread.
163 * If another looper is already associated with the thread, it is replaced.
164 *
165 * If "looper" is NULL, removes the currently associated looper.
166 */
167 static void setForThread(const sp<Looper>& looper);
168
169 /**
170 * Returns the looper associated with the calling thread, or NULL if
171 * there is not one.
172 */
173 static sp<Looper> getForThread();
174
175private:
176 struct Request {
177 int fd;
178 int ident;
179 ALooper_callbackFunc callback;
180 void* data;
181 };
182
183 struct Response {
184 int events;
185 Request request;
186 };
187
188 const bool mAllowNonCallbacks; // immutable
189
190 int mEpollFd; // immutable
191 int mWakeReadPipeFd; // immutable
192 int mWakeWritePipeFd; // immutable
193
194 // Locked list of file descriptor monitoring requests.
195 Mutex mLock;
196 KeyedVector<int, Request> mRequests;
197
198 // This state is only used privately by pollOnce and does not require a lock since
199 // it runs on a single thread.
200 Vector<Response> mResponses;
201 size_t mResponseIndex;
202
203 int pollInner(int timeoutMillis);
204
205 static void threadDestructor(void *st);
206};
207
208} // namespace android
209
210#endif // UTILS_LOOPER_H