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
//! Main loop timer events.

// This file is part of the PulseAudio Rust language binding.
//
// Copyright (c) 2017 Lyndon Brown
//
// 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/>.

use capi;
use std::os::raw::c_void;
use std::rc::Rc;
pub use libc::timeval;
use super::super::api::MainloopInnerType;

pub use capi::pa_time_event as TimeEventInternal;

/// A timer event source object.
/// This acts as a safe Rust wrapper for the actual C object.
pub struct TimeEvent<T>
    where T: MainloopInnerType
{
    ptr: *mut TimeEventInternal,
    /// Source mainloop
    owner: Rc<T>,
}

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

impl<T> TimeEvent<T>
    where T: MainloopInnerType
{
    pub fn from_raw(ptr: *mut TimeEventInternal, mainloop_inner: Rc<T>) -> Self {
        assert_eq!(false, ptr.is_null());
        Self { ptr: ptr, owner: mainloop_inner }
    }

    /// Needed to support
    /// [`::context::Context::rttime_restart`](../../../context/struct.Context.html#method.rttime_restart).
    pub fn get_ptr(&self) -> *mut TimeEventInternal {
        self.ptr
    }

    /// Restart a running or expired timer event source with a new Unix time.
    pub fn restart(&self, tv: &timeval) {
        let fn_ptr = (*self.owner).get_api().time_restart.unwrap();
        fn_ptr(self.ptr, tv);
    }

    /// Set a function that is called when the timer event source is destroyed.
    /// Use this to free the userdata argument if required.
    pub fn set_destroy(&self, cb: TimeEventDestroyCb) {
        let fn_ptr = (*self.owner).get_api().time_set_destroy.unwrap();
        fn_ptr(self.ptr, Some(cb));
    }
}

impl<T> Drop for TimeEvent<T>
    where T: MainloopInnerType
{
    fn drop(&mut self) {
        let fn_ptr = (*self.owner).get_api().time_free.unwrap();
        fn_ptr(self.ptr);
    }
}