libpulse_binding/mainloop/
signal.rs

1// Copyright 2017 Lyndon Brown
2//
3// This file is part of the PulseAudio Rust language binding.
4//
5// Licensed under the MIT license or the Apache license (version 2.0), at your option. You may not
6// copy, modify, or distribute this file except in compliance with said license. You can find copies
7// of these licenses either in the LICENSE-MIT and LICENSE-APACHE files, or alternatively at
8// <http://opensource.org/licenses/MIT> and <http://www.apache.org/licenses/LICENSE-2.0>
9// respectively.
10//
11// Portions of documentation are copied from the LGPL 2.1+ licensed PulseAudio C headers on a
12// fair-use basis, as discussed in the overall project readme (available in the git repository).
13
14//! UNIX signal support for main loops.
15//!
16//! # Overview
17//!
18//! In contrast to other main loop event sources such as timer and IO events, UNIX signal support
19//! requires modification of the global process environment. Due to this the generic main loop
20//! abstraction layer as defined in [`mainloop::api`](mod@crate::mainloop::api) doesn’t have direct
21//! support for UNIX signals. However, you may hook signal support into an abstract main loop via
22//! the routines defined herein.
23
24use std::os::raw::c_void;
25use std::ptr::null_mut;
26use capi::pa_signal_event as EventInternal;
27use crate::error::PAErr;
28use crate::callbacks::MultiUseCallback;
29use crate::mainloop::api::{ApiInternal, MainloopInnerType, Mainloop as MainloopTrait};
30
31/// An opaque UNIX signal event source object.
32///
33/// Note: Saves a copy of the closure callbacks, which it frees on drop.
34pub struct Event {
35    /// The actual C object.
36    ptr: *mut EventInternal,
37    /// Saved multi-use state callback closure, for later destruction.
38    _signal_cb: SignalCb,
39}
40
41type SignalCb = MultiUseCallback<dyn FnMut(i32), extern "C" fn(*const ApiInternal,
42    *mut EventInternal, i32, *mut c_void)>;
43
44/// Trait with signal handling, for mainloops.
45pub trait MainloopSignals : MainloopTrait {
46    /// Initializes the UNIX signal subsystem and bind it to the specified main loop.
47    fn init_signals(&mut self) -> Result<(), PAErr> {
48        let inner = self.inner();
49        let api = inner.get_api();
50        match unsafe { capi::pa_signal_init(api.into()) } {
51            0 => Ok(()),
52            e => Err(PAErr(e)),
53        }
54    }
55
56    /// Cleans up the signal subsystem.
57    #[inline]
58    fn signals_done(&self) {
59        unsafe { capi::pa_signal_done(); }
60    }
61}
62
63impl Event {
64    /// Creates a new UNIX signal event source object.
65    ///
66    /// The callback must accept an integer which represents the signal.
67    pub fn new<F>(sig: i32, callback: F) -> Self
68        where F: FnMut(i32) + 'static
69    {
70        let saved = SignalCb::new(Some(Box::new(callback)));
71        let (cb_fn, cb_data) = saved.get_capi_params(signal_cb_proxy);
72        let ptr = unsafe { capi::pa_signal_new(sig, cb_fn, cb_data) };
73        Self { ptr: ptr, _signal_cb: saved }
74    }
75}
76
77impl Drop for Event {
78    fn drop(&mut self) {
79        unsafe { capi::pa_signal_free(self.ptr) };
80        self.ptr = null_mut::<EventInternal>();
81    }
82}
83
84/// Proxy for signal callbacks.
85///
86/// Warning: This is for multi-use cases! It does **not** destroy the actual closure callback, which
87/// must be accomplished separately to avoid a memory leak.
88extern "C"
89fn signal_cb_proxy(_api: *const ApiInternal, _e: *mut EventInternal, sig: i32,
90    userdata: *mut c_void)
91{
92    let _ = std::panic::catch_unwind(|| {
93        let callback = SignalCb::get_callback(userdata);
94        (callback)(sig);
95    });
96}