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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright 2017 Lyndon Brown
//
// This file is part of the PulseAudio Rust language binding.
//
// This library is free software; you can redistribute it and/or modify it under the terms of the
// GNU Lesser General Public License as published by the Free Software Foundation; either version
// 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with this library;
// if not, see <http://www.gnu.org/licenses/>.

//! Main loop abstraction layer API.

use std;
use capi;
use std::os::raw::c_void;
use std::rc::Rc;
use libc::timeval;
use super::events::io::{IoEvent, IoEventRef, IoEventInternal, IoEventFlagSet};
use super::events::timer::{TimeEvent, TimeEventRef, TimeEventInternal};
use super::events::deferred::{DeferEvent, DeferEventRef, DeferEventInternal};
use time::{UnixTs, MonotonicTs, Timeval, USEC_INVALID};

pub(crate) use capi::pa_mainloop_api as ApiInternal;

/// This enables generic type enforcement with the opaque C objects.
pub trait MainloopInternalType {}

/// This enables generic type enforcement with MainloopInner objects, and describes mandatory
/// accessors for the internal pointers, allowing access to these pointers across the generic
/// implementations to work.
pub trait MainloopInnerType {
    type I: MainloopInternalType;

    /// Return opaque main loop object pointer.
    fn get_ptr(&self) -> *mut Self::I;

    /// Return main loop API object pointer.
    fn get_api(&self) -> &MainloopApi;

    /// Returns `true` if the mainloop implementation supports monotonic based time events.
    fn supports_rtclock(&self) -> bool;
}

/// Mainloop inner wrapper.
///
/// This contains the actual main loop object pointers, holding both the pointer to the actual
/// opaque main loop C object, and the pointer to the associated API vtable.
///
/// An instance of this type will be held, in an `Rc` ref counted wrapper both in an outer Mainloop
/// wrapper, and by all event objects. With event objects holding a ref-counted copy, this both
/// gives event objects access to the API pointer, which they need, and also it allows us to ensure
/// that event objects do not outlive the main loop object (which internally owns the API object),
/// and thus ensures correct destruction order of event and main loop objects.
pub struct MainloopInner<T>
    where T: MainloopInternalType
{
    /// An opaque main loop object.
    pub ptr: *mut T,

    /// The abstract main loop API vtable for the GLIB main loop object. No need to free this API as
    /// it is owned by the loop and is destroyed when the loop is freed.
    pub api: *const MainloopApi,

    /// All implementations must provide a drop method, to be called from an actual drop call.
    pub dropfn: fn(&mut MainloopInner<T>),

    /// Whether or not the implementation supports monotonic based time events. (`true` if so).
    pub supports_rtclock: bool,
}

impl<T> Drop for MainloopInner<T>
    where T: MainloopInternalType
{
    fn drop(&mut self) {
        (self.dropfn)(self);
    }
}

/// This is the actual implementation of the ‘inner type’ trait.
///
/// It is not possible to replace this with ‘default’ method implementations within the trait itself
/// since the trait does not know about the existence of the struct attributes being accessed.
impl<T> MainloopInnerType for MainloopInner<T>
    where T: MainloopInternalType
{
    type I = T;

    /// Gets opaque main loop object pointer.
    fn get_ptr(&self) -> *mut T {
        self.ptr
    }

    /// Gets main loop API object pointer.
    fn get_api(&self) -> &MainloopApi {
        assert!(!self.api.is_null());
        unsafe { &*self.api }
    }

    fn supports_rtclock(&self) -> bool {
        self.supports_rtclock
    }
}

pub trait Mainloop {
    type MI: MainloopInnerType;

    fn inner(&self) -> Rc<Self::MI>;

    /// Creates a new IO event.
    ///
    /// **Note**: You must ensure that the returned event object lives for as long as you want its
    /// event(s) to fire, as its `Drop` implementation destroys the event source. I.e. if you create
    /// a new event, but then immediately drop the object returned here, no event will fire!
    ///
    /// The given callback must accept three parameters, an [`IoEventRef`] object, a copy of the
    /// given file descriptor, and an event flag set, indicating the event(s) that occurred. The
    /// [`DeferEventRef`] object gives you some opportunity to manage the event source from within
    /// it’s callback execution.
    ///
    /// [`IoEventRef`]: ../events/io/struct.IoEventRef.html
    fn new_io_event(&mut self, fd: i32, events: IoEventFlagSet,
        mut callback: Box<dyn FnMut(IoEventRef<Self::MI>, i32, IoEventFlagSet) + 'static>)
        -> Option<IoEvent<Self::MI>>
    {
        let inner_for_wrapper = self.inner();
        let wrapper_cb = Box::new(move |ptr, fd, flags| {
            let ref_obj = IoEventRef::<Self::MI>::from_raw(ptr, Rc::clone(&inner_for_wrapper));
            callback(ref_obj, fd, flags);
        });

        let to_save = super::events::io::EventCb::new(Some(wrapper_cb));
        let (cb_fn, cb_data) = to_save.get_capi_params(super::events::io::event_cb_proxy);

        let inner = self.inner();
        let api = inner.get_api();
        let fn_ptr = api.io_new.unwrap();
        let ptr = fn_ptr(api, fd, events, cb_fn, cb_data);
        match ptr.is_null() {
            false => Some(IoEvent::<Self::MI>::from_raw(ptr, Rc::clone(&inner), to_save)),
            true => None,
        }
    }

    /// Creates a new timer event.
    ///
    /// **Note**: You must ensure that the returned event object lives for as long as you want its
    /// event(s) to fire, as its `Drop` implementation destroys the event source. I.e. if you create
    /// a new event, but then immediately drop the object returned here, no event will fire!
    ///
    /// The callback must take a [`TimeEventRef`] object, which gives you some opportunity to
    /// manage the event source from within it’s callback execution.
    ///
    /// Example event set to fire in five seconds time:
    ///
    /// ```rust,ignore
    /// use pulse::time::{UnixTs, MicroSeconds, MICROS_PER_SEC};
    /// let _t_event = mainloop.new_timer_event(
    ///     &(UnixTs::now() + MicroSeconds(5 * MICROS_PER_SEC)),
    ///     Box::new(|| { println!("Timer event fired!"); }));
    /// ```
    ///
    /// [`TimeEventRef`]: ../events/timer/struct.TimeEventRef.html
    fn new_timer_event(&mut self, tv: &UnixTs,
        mut callback: Box<dyn FnMut(TimeEventRef<Self::MI>) + 'static>)
        -> Option<TimeEvent<Self::MI>>
    {
        let inner_for_wrapper = self.inner();
        let wrapper_cb = Box::new(move |ptr| {
            let ref_obj = TimeEventRef::<Self::MI>::from_raw(ptr, Rc::clone(&inner_for_wrapper));
            callback(ref_obj);
        });

        let to_save = super::events::timer::EventCb::new(Some(wrapper_cb));
        let (cb_fn, cb_data) = to_save.get_capi_params(super::events::timer::event_cb_proxy);

        let inner = self.inner();
        let api = inner.get_api();
        let fn_ptr = api.time_new.unwrap();
        let ptr = fn_ptr(api, &(tv.0).0, cb_fn, cb_data);
        match ptr.is_null() {
            false => Some(TimeEvent::<Self::MI>::from_raw(ptr, Rc::clone(&inner), to_save)),
            true => None,
        }
    }

    /// Creates a new monotonic-based timer event.
    ///
    /// Asserts that `t` is not `USEC_INVALID`.
    ///
    /// This is an alternative to the `new_timer_event` method, taking a monotonic based time value.
    ///
    /// **Note**: You must ensure that the returned event object lives for as long as you want its
    /// event(s) to fire, as its `Drop` implementation destroys the event source. I.e. if you create
    /// a new event, but then immediately drop the object returned here, no event will fire!
    ///
    /// The callback must take a [`TimeEventRef`] object, which gives you some opportunity to
    /// manage the event source from within it’s callback execution.
    ///
    /// Example event set to fire in five seconds time:
    ///
    /// ```rust,ignore
    /// use pulse::time::{MonotonicTs, MicroSeconds, MICROS_PER_SEC};
    /// let _t_event = mainloop.new_timer_event_rt(
    ///     MonotonicTs::now() + MicroSeconds(5 * MICROS_PER_SEC),
    ///     Box::new(|| { println!("Timer event fired!"); }));
    /// ```
    ///
    /// [`TimeEventRef`]: ../events/timer/struct.TimeEventRef.html
    fn new_timer_event_rt(&mut self, t: MonotonicTs,
        mut callback: Box<dyn FnMut(TimeEventRef<Self::MI>) + 'static>)
        -> Option<TimeEvent<Self::MI>>
    {
        assert_ne!(t.0, USEC_INVALID);

        let inner_for_wrapper = self.inner();
        let wrapper_cb = Box::new(move |ptr| {
            let ref_obj = TimeEventRef::<Self::MI>::from_raw(ptr, Rc::clone(&inner_for_wrapper));
            callback(ref_obj);
        });

        let to_save = super::events::timer::EventCb::new(Some(wrapper_cb));
        let (cb_fn, cb_data) = to_save.get_capi_params(super::events::timer::event_cb_proxy);

        let inner = self.inner();

        let mut tv = Timeval::new_zero();
        tv.set_rt(t.0, inner.supports_rtclock());

        let api = inner.get_api();
        let fn_ptr = api.time_new.unwrap();
        let ptr = fn_ptr(api, &tv.0, cb_fn, cb_data);
        match ptr.is_null() {
            false => Some(TimeEvent::<Self::MI>::from_raw(ptr, Rc::clone(&inner), to_save)),
            true => None,
        }
    }

    /// Creates a new deferred event.
    ///
    /// **Note**: You must ensure that the returned event object lives for as long as you want its
    /// event(s) to fire, as its `Drop` implementation destroys the event source. I.e. if you create
    /// a new event, but then immediately drop the object returned here, no event will fire!
    ///
    /// The callback must take a [`DeferEventRef`] object, which gives you some opportunity to
    /// manage the event source from within it’s callback execution.
    ///
    /// [`DeferEventRef`]: ../events/deferred/struct.DeferEventRef.html
    fn new_deferred_event(&mut self,
        mut callback: Box<dyn FnMut(DeferEventRef<Self::MI>) + 'static>)
        -> Option<DeferEvent<Self::MI>>
    {
        let inner_for_wrapper = self.inner();
        let wrapper_cb = Box::new(move |ptr| {
            let ref_obj = DeferEventRef::<Self::MI>::from_raw(ptr, Rc::clone(&inner_for_wrapper));
            callback(ref_obj);
        });

        let to_save = super::events::deferred::EventCb::new(Some(wrapper_cb));
        let (cb_fn, cb_data) = to_save.get_capi_params(super::events::deferred::event_cb_proxy);

        let inner = self.inner();
        let api = inner.get_api();
        let fn_ptr = api.defer_new.unwrap();
        let ptr = fn_ptr(api, cb_fn, cb_data);
        match ptr.is_null() {
            false => Some(DeferEvent::<Self::MI>::from_raw(ptr, Rc::clone(&inner), to_save)),
            true => None,
        }
    }

    /// Runs the specified callback once from the main loop using an anonymous defer event.
    ///
    /// If the mainloop runs in a different thread, you need to follow the mainloop implementation’s
    /// rules regarding how to safely create defer events. In particular, if you’re using
    /// [`::mainloop::threaded`](../threaded/index.html), you must lock the mainloop before calling
    /// this function.
    fn once_event(&mut self, callback: Box<dyn FnMut() + 'static>) {
        let (cb_fn, cb_data): (Option<extern "C" fn(_, _)>, _) =
            ::callbacks::get_su_capi_params::<_, _>(Some(callback), once_cb_proxy);

        let inner = self.inner();
        let api = inner.get_api();
        unsafe { capi::pa_mainloop_api_once(api.as_ref(), cb_fn, cb_data) };
    }

    /// Calls quit
    fn quit(&mut self, retval: ::def::Retval) {
        let inner = self.inner();
        let api = inner.get_api();
        let fn_ptr = api.quit.unwrap();
        fn_ptr(api, retval.0);
    }
}

/// An IO event callback prototype.
pub type IoEventCb = extern "C" fn(a: *const MainloopApi, e: *mut IoEventInternal, fd: i32,
    events: IoEventFlagSet, userdata: *mut c_void);
/// A IO event destroy callback prototype.
pub type IoEventDestroyCb = extern "C" fn(a: *const MainloopApi, e: *mut IoEventInternal,
    userdata: *mut c_void);

/// A time event callback prototype.
pub type TimeEventCb = extern "C" fn(a: *const MainloopApi, e: *mut TimeEventInternal,
    tv: *const timeval, userdata: *mut c_void);
/// A time event destroy callback prototype.
pub type TimeEventDestroyCb = extern "C" fn(a: *const MainloopApi, e: *mut TimeEventInternal,
    userdata: *mut c_void);

/// A defer event callback prototype.
pub type DeferEventCb = extern "C" fn(a: *const MainloopApi, e: *mut DeferEventInternal,
    userdata: *mut c_void);
/// A defer event destroy callback prototype.
pub type DeferEventDestroyCb = extern "C" fn(a: *const MainloopApi, e: *mut DeferEventInternal,
    userdata: *mut c_void);

/// An abstract mainloop API vtable
#[repr(C)]
pub struct MainloopApi {
    /* NOTE: This struct must be directly usable by the C API, thus same attributes/layout/etc */

    /// A pointer to some private, arbitrary data of the main loop implementation.
    pub userdata: *mut c_void,

    /// Creates a new IO event source object.
    pub io_new: Option<extern "C" fn(a: *const MainloopApi, fd: i32, events: IoEventFlagSet,
        cb: Option<IoEventCb>, userdata: *mut c_void) -> *mut IoEventInternal>,
    /// Enables or disables IO events on this object.
    pub io_enable: Option<extern "C" fn(e: *mut IoEventInternal, events: IoEventFlagSet)>,
    /// Frees a IO event source object.
    pub io_free: Option<extern "C" fn(e: *mut IoEventInternal)>,
    /// Sets a function that is called when the IO event source is destroyed. Use this to free the
    /// `userdata` argument if required.
    pub io_set_destroy: Option<extern "C" fn(e: *mut IoEventInternal, cb: Option<IoEventDestroyCb>)>,

    /// Creates a new timer event source object for the specified Unix time.
    pub time_new: Option<extern "C" fn(a: *const MainloopApi, tv: *const timeval,
        cb: Option<TimeEventCb>, userdata: *mut c_void) -> *mut TimeEventInternal>,
    /// Restarts a running or expired timer event source with a new Unix time.
    pub time_restart: Option<extern "C" fn(e: *mut TimeEventInternal, tv: *const timeval)>,
    /// Frees a deferred timer event source object.
    pub time_free: Option<extern "C" fn(e: *mut TimeEventInternal)>,
    /// Sets a function that is called when the timer event source is destroyed. Use this to free
    /// the `userdata` argument if required.
    pub time_set_destroy: Option<extern "C" fn(e: *mut TimeEventInternal,
        cb: Option<TimeEventDestroyCb>)>,

    /// Creates a new deferred event source object.
    pub defer_new: Option<extern "C" fn(a: *const MainloopApi, cb: Option<DeferEventCb>,
        userdata: *mut c_void) -> *mut DeferEventInternal>,
    /// Enables or disables a deferred event source temporarily.
    pub defer_enable: Option<extern "C" fn(e: *mut DeferEventInternal, b: i32)>,
    /// Frees a deferred event source object.
    pub defer_free: Option<extern "C" fn(e: *mut DeferEventInternal)>,
    /// Sets a function that is called when the deferred event source is
    /// destroyed. Use this to free the `userdata` argument if required.
    pub defer_set_destroy: Option<extern "C" fn(e: *mut DeferEventInternal,
        cb: Option<DeferEventDestroyCb>)>,

    /// Exits the main loop and return the specified retval.
    pub quit: Option<extern "C" fn(a: *const MainloopApi, retval: ::def::RetvalActual)>,
}

/// Test size is equal to `sys` equivalent (duplicated here for different documentation)
#[test]
fn api_compare_capi(){
    assert_eq!(std::mem::size_of::<ApiInternal>(), std::mem::size_of::<capi::pa_mainloop_api>());
    assert_eq!(std::mem::align_of::<ApiInternal>(), std::mem::align_of::<capi::pa_mainloop_api>());
}

impl AsRef<capi::pa_mainloop_api> for MainloopApi {
    #[inline]
    fn as_ref(&self) -> &capi::pa_mainloop_api {
        unsafe { &*(self as *const Self as *const capi::pa_mainloop_api) }
    }
}

impl<'a> From<*const ApiInternal> for &'a MainloopApi {
    #[inline]
    fn from(a: *const ApiInternal) -> Self {
        unsafe { std::mem::transmute(a) }
    }
}
impl<'a> From<&'a MainloopApi> for *const ApiInternal {
    #[inline]
    fn from(a: &'a MainloopApi) -> Self {
        unsafe { std::mem::transmute(a) }
    }
}

/// Proxy for anonymous ‘once’ deferred event callbacks.
///
/// Warning: This is for single-use cases only! It destroys the actual closure callback.
extern "C"
fn once_cb_proxy(_: *const ApiInternal, userdata: *mut c_void) {
    let _ = std::panic::catch_unwind(|| {
        // Note, destroys closure callback after use - restoring outer box means it gets dropped
        let mut callback = ::callbacks::get_su_callback::<dyn FnMut()>(userdata);
        (callback)();
    });
}