1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use bitflags::bitflags;
use std::convert::TryInto;
use std::mem::ManuallyDrop;
use std::os::raw::c_void;
use std::os::unix::io::RawFd;
use std::ptr;
use std::ptr::NonNull;
use std::time::Duration;
use thiserror::Error;
#[derive(Debug)]
pub struct ThreadLooper {
_marker: std::marker::PhantomData<*mut ()>,
foreign: ForeignLooper,
}
bitflags! {
pub struct FdEvent: u32 {
const INPUT = ffi::ALOOPER_EVENT_INPUT;
const OUTPUT = ffi::ALOOPER_EVENT_OUTPUT;
const ERROR = ffi::ALOOPER_EVENT_ERROR;
const HANGUP = ffi::ALOOPER_EVENT_HANGUP;
const INVALID = ffi::ALOOPER_EVENT_INVALID;
}
}
#[derive(Debug)]
pub enum Poll {
Wake,
Callback,
Timeout,
Event {
ident: i32,
fd: RawFd,
events: FdEvent,
data: *mut c_void,
},
}
#[derive(Debug, Copy, Clone, Error)]
#[error("Android Looper error")]
pub struct LooperError;
impl ThreadLooper {
pub fn prepare() -> Self {
unsafe {
let ptr = ffi::ALooper_prepare(ffi::ALOOPER_PREPARE_ALLOW_NON_CALLBACKS as _);
let foreign = ForeignLooper::from_ptr(NonNull::new(ptr).expect("looper non null"));
Self {
_marker: std::marker::PhantomData,
foreign,
}
}
}
pub fn for_thread() -> Option<Self> {
Some(Self {
_marker: std::marker::PhantomData,
foreign: ForeignLooper::for_thread()?,
})
}
fn poll_once_ms(&self, ms: i32) -> Result<Poll, LooperError> {
let mut fd: RawFd = -1;
let mut events: i32 = -1;
let mut data: *mut c_void = ptr::null_mut();
match unsafe { ffi::ALooper_pollOnce(ms, &mut fd, &mut events, &mut data) } {
ffi::ALOOPER_POLL_WAKE => Ok(Poll::Wake),
ffi::ALOOPER_POLL_CALLBACK => Ok(Poll::Callback),
ffi::ALOOPER_POLL_TIMEOUT => Ok(Poll::Timeout),
ffi::ALOOPER_POLL_ERROR => Err(LooperError),
ident if ident >= 0 => Ok(Poll::Event {
ident,
fd,
events: FdEvent::from_bits(events as u32)
.expect("poll event contains unknown bits"),
data,
}),
_ => unreachable!(),
}
}
#[inline]
pub fn poll_once(&self) -> Result<Poll, LooperError> {
self.poll_once_ms(-1)
}
#[inline]
pub fn poll_once_timeout(&self, timeout: Duration) -> Result<Poll, LooperError> {
self.poll_once_ms(
timeout
.as_millis()
.try_into()
.expect("Supplied timeout is too large"),
)
}
fn poll_all_ms(&self, ms: i32) -> Result<Poll, LooperError> {
let mut fd: RawFd = -1;
let mut events: i32 = -1;
let mut data: *mut c_void = ptr::null_mut();
match unsafe { ffi::ALooper_pollAll(ms, &mut fd, &mut events, &mut data) } {
ffi::ALOOPER_POLL_WAKE => Ok(Poll::Wake),
ffi::ALOOPER_POLL_TIMEOUT => Ok(Poll::Timeout),
ffi::ALOOPER_POLL_ERROR => Err(LooperError),
ident if ident >= 0 => Ok(Poll::Event {
ident,
fd,
events: FdEvent::from_bits(events as u32)
.expect("poll event contains unknown bits"),
data,
}),
_ => unreachable!(),
}
}
#[inline]
pub fn poll_all(&self) -> Result<Poll, LooperError> {
self.poll_all_ms(-1)
}
#[inline]
pub fn poll_all_timeout(&self, timeout: Duration) -> Result<Poll, LooperError> {
self.poll_all_ms(
timeout
.as_millis()
.try_into()
.expect("Supplied timeout is too large"),
)
}
pub fn as_foreign(&self) -> &ForeignLooper {
&self.foreign
}
pub fn into_foreign(self) -> ForeignLooper {
self.foreign
}
}
#[derive(Debug)]
pub struct ForeignLooper {
ptr: NonNull<ffi::ALooper>,
}
unsafe impl Send for ForeignLooper {}
unsafe impl Sync for ForeignLooper {}
impl Drop for ForeignLooper {
fn drop(&mut self) {
unsafe { ffi::ALooper_release(self.ptr.as_ptr()) }
}
}
impl Clone for ForeignLooper {
fn clone(&self) -> Self {
unsafe {
ffi::ALooper_acquire(self.ptr.as_ptr());
Self { ptr: self.ptr }
}
}
}
impl ForeignLooper {
#[inline]
pub fn for_thread() -> Option<Self> {
NonNull::new(unsafe { ffi::ALooper_forThread() }).map(|ptr| unsafe { Self::from_ptr(ptr) })
}
#[inline]
pub unsafe fn from_ptr(ptr: NonNull<ffi::ALooper>) -> Self {
ffi::ALooper_acquire(ptr.as_ptr());
Self { ptr }
}
#[inline]
pub fn ptr(&self) -> NonNull<ffi::ALooper> {
self.ptr
}
pub fn wake(&self) {
unsafe { ffi::ALooper_wake(self.ptr.as_ptr()) }
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn add_fd(
&self,
fd: RawFd,
ident: i32,
events: FdEvent,
data: *mut c_void,
) -> Result<(), LooperError> {
match unsafe {
ffi::ALooper_addFd(
self.ptr.as_ptr(),
fd,
ident,
events.bits() as i32,
None,
data,
)
} {
1 => Ok(()),
-1 => Err(LooperError),
_ => unreachable!(),
}
}
pub fn add_fd_with_callback<F: FnMut(RawFd) -> bool>(
&self,
fd: RawFd,
events: FdEvent,
callback: F,
) -> Result<(), LooperError> {
extern "C" fn cb_handler<F: FnMut(RawFd) -> bool>(
fd: RawFd,
_events: i32,
data: *mut c_void,
) -> i32 {
unsafe {
let mut cb = ManuallyDrop::new(Box::<F>::from_raw(data as *mut _));
let keep_registered = cb(fd);
if !keep_registered {
ManuallyDrop::into_inner(cb);
}
keep_registered as i32
}
}
let data = Box::into_raw(Box::new(callback)) as *mut _;
match unsafe {
ffi::ALooper_addFd(
self.ptr.as_ptr(),
fd,
ffi::ALOOPER_POLL_CALLBACK,
events.bits() as i32,
Some(cb_handler::<F>),
data,
)
} {
1 => Ok(()),
-1 => Err(LooperError),
_ => unreachable!(),
}
}
}