android_looper_sys/
lib.rs

1// Copyright 2016 The android_looper_sys Developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! <a href="https://github.com/Nercury/android_looper-sys-rs">
9//! <img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_orange_ff7600.png" alt="Fork me on GitHub">
10//! </a>
11//! <style>.sidebar { margin-top: 53px }</style>
12//!
13
14#![allow(non_camel_case_types)]
15
16extern crate libc;
17#[macro_use]
18extern crate bitflags;
19
20use libc::{c_int, c_void};
21
22/**
23 * ALooper
24 *
25 * A looper is the state tracking an event loop for a thread.
26 * Loopers do not define event structures or other such things; rather
27 * they are a lower-level facility to attach one or more discrete objects
28 * listening for an event.  An "event" here is simply data available on
29 * a file descriptor: each attached object has an associated file descriptor,
30 * and waiting for "events" means (internally) polling on all of these file
31 * descriptors until one or more of them have data available.
32 *
33 * A thread can have only one ALooper associated with it.
34 */
35pub enum ALooper { }
36
37/// Option for for `ALooper_prepare()`.
38#[derive(Clone, Copy)]
39#[repr(isize)]
40pub enum LooperPrepareOpts {
41    /// `ALLOW_NON_CALLBACKS`
42    ///
43    /// Option for ALooper_prepare: this looper will accept calls to
44    /// ALooper_addFd() that do not have a callback (that is provide NULL
45    /// for the callback).  In this case the caller of ALooper_pollOnce()
46    /// or ALooper_pollAll() MUST check the return from these functions to
47    /// discover when data is available on such fds and process it.
48    AllowNonCallbacks = 1 << 0,
49    /// `0` value, allow only callbacks
50    None = 0,
51}
52
53/// Result from `ALooper_pollOnce()` and `ALooper_pollAll()`.
54#[derive(Clone, Copy)]
55#[repr(isize)]
56pub enum LooperPoll {
57    /// `ALOOPER_POLL_WAKE`
58    ///
59    /// The poll was awoken using wake() before the timeout expired
60    /// and no callbacks were executed and no other file descriptors were ready.
61    Wake = -1,
62    /// `ALOOPER_POLL_CALLBACK`
63    ///
64    /// One or more callbacks were executed.
65    Callback = -2,
66    /// `ALOOPER_POLL_TIMEOUT`
67    ///
68    /// The timeout expired.
69    Timeout = -3,
70    /// `ALOOPER_POLL_ERROR`
71    ///
72    /// An error occurred.
73    Error = -4,
74}
75
76/// Flags for file descriptor events that a looper can monitor.
77///
78/// These flag bits can be combined to monitor multiple events at once.
79pub mod event {
80    bitflags! {
81        pub struct Type: isize {
82            /// `ALOOPER_EVENT_INPUT`
83            ///
84            /// The file descriptor is available for read operations.
85            const INPUT       = 1 << 0;
86            /// `ALOOPER_EVENT_OUTPUT`
87            ///
88            /// The file descriptor is available for write operations.
89            const OUTPUT    = 1 << 1;
90            /// `ALOOPER_EVENT_ERROR`
91            ///
92            /// The file descriptor has encountered an error condition.
93            ///
94            /// The looper always sends notifications about errors; it is not necessary
95            /// to specify this event flag in the requested event set.
96            const ERROR   = 1 << 2;
97            /// `ALOOPER_EVENT_HANGUP`
98            ///
99            /// The file descriptor was hung up.
100            /// For example, indicates that the remote end of a pipe or socket was closed.
101            ///
102            /// The looper always sends notifications about hangups; it is not necessary
103            /// to specify this event flag in the requested event set.
104            const HANGUP   = 1 << 3;
105            /// `ALOOPER_EVENT_INVALID`
106            ///
107            /// The file descriptor is invalid.
108            /// For example, the file descriptor was closed prematurely.
109            ///
110            /// The looper always sends notifications about invalid file descriptors; it is not necessary
111            /// to specify this event flag in the requested event set.
112            const INVALID       = 1 << 4;
113        }
114    }
115}
116
117/**
118 * For callback-based event loops, this is the prototype of the function
119 * that is called when a file descriptor event occurs.
120 * It is given the file descriptor it is associated with,
121 * a bitmask of the poll events that were triggered (typically ALOOPER_EVENT_INPUT),
122 * and the data pointer that was originally supplied.
123 *
124 * Implementations should return 1 to continue receiving callbacks, or 0
125 * to have this file descriptor and callback unregistered from the looper.
126 */
127pub type ALooper_callbackFunc = ::std::option::Option<unsafe extern "C" fn(fd: c_int,
128                                                                             events: c_int,
129                                                                             data: *mut c_void)
130                                                                             -> c_int>;
131extern "C" {
132
133    /// Returns the looper associated with the calling thread, or NULL if
134    /// there is not one.
135    pub fn ALooper_forThread() -> *mut ALooper;
136
137    /// Prepares a looper associated with the calling thread, and returns it.
138    /// If the thread already has a looper, it is returned.  Otherwise, a new
139    /// one is created, associated with the thread, and returned.
140    ///
141    /// The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0.
142    pub fn ALooper_prepare(opts: c_int) -> *mut ALooper;
143
144    /// Acquire a reference on the given ALooper object.  This prevents the object
145    /// from being deleted until the reference is removed.  This is only needed
146    /// to safely hand an ALooper from one thread to another.
147    pub fn ALooper_acquire(looper: *mut ALooper);
148
149    /// Remove a reference that was previously acquired with ALooper_acquire().
150    pub fn ALooper_release(looper: *mut ALooper);
151    /// Waits for events to be available, with optional timeout in milliseconds.
152    /// Invokes callbacks for all file descriptors on which an event occurred.
153    ///
154    /// If the timeout is zero, returns immediately without blocking.
155    /// If the timeout is negative, waits indefinitely until an event appears.
156    ///
157    /// Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before
158    /// the timeout expired and no callbacks were invoked and no other file
159    /// descriptors were ready.
160    ///
161    /// Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked.
162    ///
163    /// Returns ALOOPER_POLL_TIMEOUT if there was no data before the given
164    /// timeout expired.
165    ///
166    /// Returns ALOOPER_POLL_ERROR if an error occurred.
167    ///
168    /// Returns a value >= 0 containing an identifier if its file descriptor has data
169    /// and it has no callback function (requiring the caller here to handle it).
170    /// In this (and only this) case outFd, outEvents and outData will contain the poll
171    /// events and data associated with the fd, otherwise they will be set to NULL.
172    ///
173    /// This method does not return until it has finished invoking the appropriate callbacks
174    /// for all file descriptors that were signalled.
175    pub fn ALooper_pollOnce(timeoutMillis: c_int,
176                            outFd: *mut c_int,
177                            outEvents: *mut c_int,
178                            outData: *mut *mut c_void)
179                            -> c_int;
180
181    /// Like ALooper_pollOnce(), but performs all pending callbacks until all
182    /// data has been consumed or a file descriptor is available with no callback.
183    /// This function will never return ALOOPER_POLL_CALLBACK.
184    pub fn ALooper_pollAll(timeoutMillis: c_int,
185                           outFd: *mut c_int,
186                           outEvents: *mut c_int,
187                           outData: *mut *mut c_void)
188                           -> c_int;
189
190    /// Wakes the poll asynchronously.
191    ///
192    /// This method can be called on any thread.
193    /// This method returns immediately.
194    pub fn ALooper_wake(looper: *mut ALooper);
195
196    /// Adds a new file descriptor to be polled by the looper.
197    /// If the same file descriptor was previously added, it is replaced.
198    ///
199    /// - "fd" is the file descriptor to be added.
200    /// - "ident" is an identifier for this event, which is returned from ALooper_pollOnce().
201    /// The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
202    /// - "events" are the poll events to wake up on.  Typically this is ALOOPER_EVENT_INPUT.
203    /// - "callback" is the function to call when there is an event on the file descriptor.
204    /// - "data" is a private data pointer to supply to the callback.
205    ///
206    /// There are two main uses of this function:
207    ///
208    /// (1) If "callback" is non-NULL, then this function will be called when there is
209    /// data on the file descriptor.  It should execute any events it has pending,
210    /// appropriately reading from the file descriptor.  The 'ident' is ignored in this case.
211    ///
212    /// (2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce
213    /// when its file descriptor has data available, requiring the caller to take
214    /// care of processing it.
215    ///
216    /// Returns 1 if the file descriptor was added or -1 if an error occurred.
217    ///
218    /// This method can be called on any thread.
219    /// This method may block briefly if it needs to wake the poll.
220    pub fn ALooper_addFd(looper: *mut ALooper,
221                         fd: c_int,
222                         ident: c_int,
223                         events: c_int,
224                         callback: ALooper_callbackFunc,
225                         data: *mut c_void)
226                         -> c_int;
227
228    /// Removes a previously added file descriptor from the looper.
229    ///
230    /// When this method returns, it is safe to close the file descriptor since the looper
231    /// will no longer have a reference to it.  However, it is possible for the callback to
232    /// already be running or for it to run one last time if the file descriptor was already
233    /// signalled.  Calling code is responsible for ensuring that this case is safely handled.
234    /// For example, if the callback takes care of removing itself during its own execution either
235    /// by returning 0 or by calling this method, then it can be guaranteed to not be invoked
236    /// again at any later time unless registered anew.
237    ///
238    /// Returns 1 if the file descriptor was removed, 0 if none was previously registered
239    /// or -1 if an error occurred.
240    ///
241    /// This method can be called on any thread.
242    ///
243    /// This method may block briefly if it needs to wake the poll.
244    pub fn ALooper_removeFd(looper: *mut ALooper, fd: c_int) -> c_int;
245}