libpulse_binding/operation.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//! Asynchronous operations.
15
16use std::os::raw::c_void;
17use std::ptr::null_mut;
18use crate::callbacks;
19
20use capi::pa_operation as OperationInternal;
21pub use capi::pa_operation_state_t as State;
22
23/// An asynchronous operation object.
24///
25/// Note: Saves a copy of active multi-use closure callbacks, which it frees on drop.
26pub struct Operation<ClosureProto: ?Sized> {
27 /// The actual C object.
28 ptr: *mut OperationInternal,
29 /// The operation’s associated closure callback.
30 /// This is a copy of the callback userdata pointer given in the C API function call that
31 /// generated the operation instance (except not cast to void). It is saved here in case the
32 /// user tries to cancel execution of the callback (with the `cancel` method), in which case we
33 /// need this in order to release the memory.
34 saved_cb: Option<*mut Box<ClosureProto>>,
35 /// Saved multi-use state callback closure, for later destruction.
36 state_cb: NotifyCb,
37}
38
39unsafe impl<ClosureProto: ?Sized> Send for Operation<ClosureProto> {}
40unsafe impl<ClosureProto: ?Sized> Sync for Operation<ClosureProto> {}
41
42type NotifyCb = callbacks::MultiUseCallback<dyn FnMut(),
43 extern "C" fn(*mut OperationInternal, *mut c_void)>;
44
45impl<ClosureProto: ?Sized> Operation<ClosureProto> {
46 /// Creates a new `Operation` from an existing [`OperationInternal`] pointer.
47 ///
48 /// We also take a copy of the closure callback pointer, in order to free the memory on
49 /// cancellation.
50 pub(crate) fn from_raw(ptr: *mut OperationInternal, saved_cb: *mut Box<ClosureProto>) -> Self {
51 assert!(!ptr.is_null());
52 let saved_cb_actual = match saved_cb.is_null() {
53 true => Some(saved_cb),
54 false => None,
55 };
56 Self { ptr: ptr, saved_cb: saved_cb_actual, state_cb: Default::default() }
57 }
58
59 /// Cancels the operation.
60 ///
61 /// Beware! This will not necessarily cancel the execution of the operation on the server side.
62 /// However it will make sure that the callback associated with this operation will not be
63 /// called any more, effectively disabling the operation from the client side’s view.
64 ///
65 /// **Warning**, you should **never** attempt to use this to cancel a callback from within the
66 /// execution of that callback itself. This should go without saying, since it makes absolutely
67 /// no sense to try and do this, but be aware that this is not supported by the C API and
68 /// **will** break things.
69 pub fn cancel(&mut self) {
70 unsafe { capi::pa_operation_cancel(self.ptr); }
71 // Release the memory allocated for the closure.
72 // Note, we `take()` here to help avoid issues if this function is mistakenly called more
73 // than once.
74 let callback = self.saved_cb.take();
75 if let Some(ptr) = callback {
76 if !ptr.is_null() {
77 drop(unsafe { Box::from_raw(ptr as *mut Box<ClosureProto>) });
78 }
79 }
80 }
81
82 /// Gets the current status of the operation.
83 #[inline]
84 pub fn get_state(&self) -> State {
85 unsafe { capi::pa_operation_get_state(self.ptr) }
86 }
87
88 /// Sets the callback function that is called when the operation state changes.
89 ///
90 /// Usually this is not necessary, since the functions that create `Operation` objects already
91 /// take a callback that is called when the operation finishes. Registering a state change
92 /// callback is mainly useful, if you want to get called back also if the operation gets
93 /// cancelled.
94 pub fn set_state_callback(&mut self, callback: Option<Box<dyn FnMut() + 'static>>) {
95 let saved = &mut self.state_cb;
96 *saved = NotifyCb::new(callback);
97 let (cb_fn, cb_data) = saved.get_capi_params(notify_cb_proxy);
98 unsafe { capi::pa_operation_set_state_callback(self.ptr, cb_fn, cb_data); }
99 }
100}
101
102impl<ClosureProto: ?Sized> Drop for Operation<ClosureProto> {
103 fn drop(&mut self) {
104 // Note, we deliberately do not destroy the `saved_cb` closure here. That should only be
105 // destroyed either separately by a callback proxy, or by the `Operation`’s `cancel` method.
106 unsafe { capi::pa_operation_unref(self.ptr) };
107 self.ptr = null_mut::<OperationInternal>();
108 }
109}
110
111/// Proxy for notification callbacks.
112///
113/// Warning: This is for multi-use cases! It does **not** destroy the actual closure callback, which
114/// must be accomplished separately to avoid a memory leak.
115extern "C"
116fn notify_cb_proxy(_: *mut OperationInternal, userdata: *mut c_void) {
117 let _ = std::panic::catch_unwind(|| {
118 let callback = NotifyCb::get_callback(userdata);
119 (callback)();
120 });
121}