gio/
cancellable.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::num::NonZeroU64;
4
5use futures_channel::oneshot;
6use futures_core::Future;
7use glib::{prelude::*, translate::*};
8
9use crate::{ffi, Cancellable};
10
11// 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);
17
18impl CancelledHandlerId {
19    // rustdoc-stripper-ignore-next
20    /// Returns the internal signal handler ID.
21    #[allow(clippy::missing_safety_doc)]
22    pub unsafe fn as_raw(&self) -> libc::c_ulong {
23        self.0.get() as libc::c_ulong
24    }
25}
26
27impl TryFromGlib<libc::c_ulong> for CancelledHandlerId {
28    type Error = GlibNoneError;
29    #[inline]
30    unsafe fn try_from_glib(val: libc::c_ulong) -> Result<Self, GlibNoneError> {
31        NonZeroU64::new(val as _).map(Self).ok_or(GlibNoneError)
32    }
33}
34
35pub 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")]
55    fn connect_cancelled<F: FnOnce(&Self) + Send + 'static>(
56        &self,
57        callback: F,
58    ) -> Option<CancelledHandlerId> {
59        unsafe extern "C" fn connect_trampoline<P: IsA<Cancellable>, F: FnOnce(&P)>(
60            this: *mut ffi::GCancellable,
61            callback: glib::ffi::gpointer,
62        ) {
63            let callback: &mut Option<F> = &mut *(callback as *mut Option<F>);
64            let callback = callback
65                .take()
66                .expect("Cancellable::cancel() closure called multiple times");
67            callback(Cancellable::from_glib_borrow(this).unsafe_cast_ref())
68        }
69
70        unsafe extern "C" fn destroy_closure<F>(ptr: glib::ffi::gpointer) {
71            let _ = Box::<Option<F>>::from_raw(ptr as *mut _);
72        }
73
74        let callback: Box<Option<F>> = Box::new(Some(callback));
75        unsafe {
76            from_glib(ffi::g_cancellable_connect(
77                self.as_ptr() as *mut _,
78                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
79                    connect_trampoline::<Self, F> as *const (),
80                )),
81                Box::into_raw(callback) as *mut _,
82                Some(destroy_closure::<F>),
83            ))
84        }
85    }
86    // rustdoc-stripper-ignore-next
87    /// Local variant of [`Self::connect_cancelled`].
88    #[doc(alias = "g_cancellable_connect")]
89    fn connect_cancelled_local<F: FnOnce(&Self) + 'static>(
90        &self,
91        callback: F,
92    ) -> Option<CancelledHandlerId> {
93        let callback = glib::thread_guard::ThreadGuard::new(callback);
94
95        self.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")]
106    fn disconnect_cancelled(&self, id: CancelledHandlerId) {
107        unsafe { 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.
112    fn future(&self) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>> {
113        let cancellable = self.as_ref().clone();
114        let (tx, rx) = oneshot::channel();
115        let id = cancellable.connect_cancelled(move |_| {
116            let _ = tx.send(());
117        });
118        Box::pin(async move {
119            rx.await.unwrap();
120            if let Some(id) = id {
121                cancellable.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")]
135    fn set_error_if_cancelled(&self) -> Result<(), glib::Error> {
136        unsafe {
137            let mut error = std::ptr::null_mut();
138            let is_ok = ffi::g_cancellable_set_error_if_cancelled(
139                self.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.
144            debug_assert_eq!(is_ok == glib::ffi::GFALSE, error.is_null());
145            if error.is_null() {
146                Ok(())
147            } else {
148                Err(from_glib_full(error))
149            }
150        }
151    }
152}
153
154impl<O: IsA<Cancellable>> CancellableExtManual for O {}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    use crate::prelude::*;
161
162    #[test]
163    fn cancellable_callback() {
164        let c = Cancellable::new();
165        let id = c.connect_cancelled(|_| {});
166        c.cancel(); // if it doesn't crash at this point, then we're good to go!
167        c.disconnect_cancelled(id.unwrap());
168    }
169
170    #[test]
171    fn cancellable_callback_local() {
172        let c = Cancellable::new();
173        let id = c.connect_cancelled_local(|_| {});
174        c.cancel(); // if it doesn't crash at this point, then we're good to go!
175        c.disconnect_cancelled(id.unwrap());
176    }
177
178    #[test]
179    fn cancellable_error_if_cancelled() {
180        let c = Cancellable::new();
181        c.cancel();
182        assert!(c.set_error_if_cancelled().is_err());
183    }
184
185    #[test]
186    fn cancellable_future() {
187        let c = Cancellable::new();
188        c.cancel();
189        glib::MainContext::new().block_on(c.future());
190    }
191
192    #[test]
193    fn cancellable_future_thread() {
194        let cancellable = Cancellable::new();
195        let c = cancellable.clone();
196        std::thread::spawn(move || c.cancel()).join().unwrap();
197        glib::MainContext::new().block_on(cancellable.future());
198    }
199
200    #[test]
201    fn cancellable_future_delayed() {
202        let ctx = glib::MainContext::new();
203        let c = Cancellable::new();
204        let (tx, rx) = oneshot::channel();
205        {
206            let 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}