1// Take a look at the license at the top of the repository in the LICENSE file.
23use std::num::NonZeroU64;
45use futures_channel::oneshot;
6use futures_core::Future;
7use glib::{prelude::*, translate::*};
89use crate::{ffi, Cancellable};
1011// rustdoc-stripper-ignore-next
12/// The id of a cancelled handler that is returned by `CancellableExtManual::connect`. This type is
13/// analogous to [`glib::SignalHandlerId`].
14#[derive(Debug, Eq, PartialEq)]
15#[repr(transparent)]
16pub struct CancelledHandlerId(NonZeroU64);
1718impl CancelledHandlerId {
19// rustdoc-stripper-ignore-next
20/// Returns the internal signal handler ID.
21#[allow(clippy::missing_safety_doc)]
22pub unsafe fn as_raw(&self) -> libc::c_ulong {
23self.0.get() as libc::c_ulong
24 }
25}
2627impl TryFromGlib<libc::c_ulong> for CancelledHandlerId {
28type Error = GlibNoneError;
29#[inline]
30unsafe fn try_from_glib(val: libc::c_ulong) -> Result<Self, GlibNoneError> {
31NonZeroU64::new(valas _).map(Self).ok_or(GlibNoneError)
32 }
33}
3435pub trait CancellableExtManual: IsA<Cancellable> {
36// rustdoc-stripper-ignore-next
37/// Convenience function to connect to the `signal::Cancellable::cancelled` signal. Also
38 /// handles the race condition that may happen if the cancellable is cancelled right before
39 /// connecting. If the operation is cancelled from another thread, `callback` will be called
40 /// in the thread that cancelled the operation, not the thread that is running the operation.
41 /// This may be the main thread, so the callback should not do something that can block.
42 ///
43 /// `callback` is called at most once, either directly at the time of the connect if `self` is
44 /// already cancelled, or when `self` is cancelled in some thread.
45 ///
46 /// Since GLib 2.40, the lock protecting `self` is not held when `callback` is invoked. This
47 /// lifts a restriction in place for earlier GLib versions which now makes it easier to write
48 /// cleanup code that unconditionally invokes e.g.
49 /// [`CancellableExt::cancel()`][crate::prelude::CancellableExt::cancel()].
50 ///
51 /// # Returns
52 ///
53 /// The id of the signal handler or `None` if `self` has already been cancelled.
54#[doc(alias = "g_cancellable_connect")]
55fn connect_cancelled<F: FnOnce(&Self) + Send + 'static>(
56&self,
57 callback: F,
58 ) -> Option<CancelledHandlerId> {
59unsafe extern "C" fn connect_trampoline<P: IsA<Cancellable>, F: FnOnce(&P)>(
60 this: *mut ffi::GCancellable,
61 callback: glib::ffi::gpointer,
62 ) {
63let callback: &mut Option<F> = &mut *(callbackas *mut Option<F>);
64let callback = callback65 .take()
66 .expect("Cancellable::cancel() closure called multiple times");
67callback(Cancellable::from_glib_borrow(this).unsafe_cast_ref())
68 }
6970unsafe extern "C" fn destroy_closure<F>(ptr: glib::ffi::gpointer) {
71let _ = Box::<Option<F>>::from_raw(ptras *mut _);
72 }
7374let callback: Box<Option<F>> = Box::new(Some(callback));
75unsafe {
76from_glib(ffi::g_cancellable_connect(
77self.as_ptr() as *mut _,
78Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
79connect_trampoline::<Self, F> as *const (),
80 )),
81Box::into_raw(callback) as *mut _,
82Some(destroy_closure::<F>),
83 ))
84 }
85 }
86// rustdoc-stripper-ignore-next
87/// Local variant of [`Self::connect_cancelled`].
88#[doc(alias = "g_cancellable_connect")]
89fn connect_cancelled_local<F: FnOnce(&Self) + 'static>(
90&self,
91 callback: F,
92 ) -> Option<CancelledHandlerId> {
93let callback = glib::thread_guard::ThreadGuard::new(callback);
9495self.connect_cancelled(move |obj| (callback.into_inner())(obj))
96 }
97// rustdoc-stripper-ignore-next
98/// Disconnects a handler from a cancellable instance. Additionally, in the event that a signal
99 /// handler is currently running, this call will block until the handler has finished. Calling
100 /// this function from a callback registered with [`Self::connect_cancelled`] will therefore
101 /// result in a deadlock.
102 ///
103 /// This avoids a race condition where a thread cancels at the same time as the cancellable
104 /// operation is finished and the signal handler is removed.
105#[doc(alias = "g_cancellable_disconnect")]
106fn disconnect_cancelled(&self, id: CancelledHandlerId) {
107unsafe { ffi::g_cancellable_disconnect(self.as_ptr() as *mut _, id.as_raw()) };
108 }
109// rustdoc-stripper-ignore-next
110/// Returns a `Future` that completes when the cancellable becomes cancelled. Completes
111 /// immediately if the cancellable is already cancelled.
112fn future(&self) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>> {
113let cancellable = self.as_ref().clone();
114let (tx, rx) = oneshot::channel();
115let id = cancellable.connect_cancelled(move |_| {
116let _ = tx.send(());
117 });
118Box::pin(async move {
119rx.await.unwrap();
120if let Some(id) = id {
121cancellable.disconnect_cancelled(id);
122 }
123 })
124 }
125// rustdoc-stripper-ignore-next
126/// Set an error if the cancellable is already cancelled.
127// rustdoc-stripper-ignore-next-stop
128/// If the @self is cancelled, sets the error to notify
129 /// that the operation was cancelled.
130 ///
131 /// # Returns
132 ///
133 /// [`true`] if @self was cancelled, [`false`] if it was not
134#[doc(alias = "g_cancellable_set_error_if_cancelled")]
135fn set_error_if_cancelled(&self) -> Result<(), glib::Error> {
136unsafe {
137let mut error = std::ptr::null_mut();
138let is_ok = ffi::g_cancellable_set_error_if_cancelled(
139self.as_ref().to_glib_none().0,
140&mut error,
141 );
142// Here's the special case, this function has an inverted
143 // return value for the error case.
144debug_assert_eq!(is_ok == glib::ffi::GFALSE, error.is_null());
145if error.is_null() {
146Ok(())
147 } else {
148Err(from_glib_full(error))
149 }
150 }
151 }
152}
153154impl<O: IsA<Cancellable>> CancellableExtManualfor O {}
155156#[cfg(test)]
157mod tests {
158use super::*;
159160use crate::prelude::*;
161162#[test]
163fn cancellable_callback() {
164let c = Cancellable::new();
165let id = c.connect_cancelled(|_| {});
166 c.cancel(); // if it doesn't crash at this point, then we're good to go!
167c.disconnect_cancelled(id.unwrap());
168 }
169170#[test]
171fn cancellable_callback_local() {
172let c = Cancellable::new();
173let id = c.connect_cancelled_local(|_| {});
174 c.cancel(); // if it doesn't crash at this point, then we're good to go!
175c.disconnect_cancelled(id.unwrap());
176 }
177178#[test]
179fn cancellable_error_if_cancelled() {
180let c = Cancellable::new();
181 c.cancel();
182assert!(c.set_error_if_cancelled().is_err());
183 }
184185#[test]
186fn cancellable_future() {
187let c = Cancellable::new();
188 c.cancel();
189 glib::MainContext::new().block_on(c.future());
190 }
191192#[test]
193fn cancellable_future_thread() {
194let cancellable = Cancellable::new();
195let c = cancellable.clone();
196 std::thread::spawn(move || c.cancel()).join().unwrap();
197 glib::MainContext::new().block_on(cancellable.future());
198 }
199200#[test]
201fn cancellable_future_delayed() {
202let ctx = glib::MainContext::new();
203let c = Cancellable::new();
204let (tx, rx) = oneshot::channel();
205 {
206let c = c.clone();
207 ctx.spawn_local(async move {
208 c.future().await;
209 tx.send(()).unwrap();
210 });
211 }
212 std::thread::spawn(move || c.cancel()).join().unwrap();
213 ctx.block_on(rx).unwrap();
214 }
215}