|
1 | 1 | // Take a look at the license at the top of the repository in the LICENSE file.
|
2 | 2 |
|
3 | 3 | use crate::prelude::*;
|
| 4 | +use crate::Cancellable; |
| 5 | +use futures_channel::oneshot; |
| 6 | +use futures_core::Future; |
| 7 | +use glib::{translate::*, IsA}; |
| 8 | +use std::num::NonZeroU64; |
4 | 9 |
|
5 |
| -#[test] |
6 |
| -fn check_callback() { |
7 |
| - let c = crate::Cancellable::new(); |
8 |
| - c.connect_cancelled(|_| {}); |
9 |
| - c.cancel(); // if it doesn't crash at this point, then we're good to go! |
| 10 | +// rustdoc-stripper-ignore-next |
| 11 | +/// The id of a cancelled handler that is returned by `CancellableExtManual::connect`. This type is |
| 12 | +/// analogous to [`glib::SignalHandlerId`]. |
| 13 | +#[derive(Debug, Eq, PartialEq)] |
| 14 | +#[repr(transparent)] |
| 15 | +pub struct CancelledHandlerId(NonZeroU64); |
| 16 | + |
| 17 | +impl CancelledHandlerId { |
| 18 | + // rustdoc-stripper-ignore-next |
| 19 | + /// Returns the internal signal handler ID. |
| 20 | + pub unsafe fn as_raw(&self) -> libc::c_ulong { |
| 21 | + self.0.get() as libc::c_ulong |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +impl TryFromGlib<libc::c_ulong> for CancelledHandlerId { |
| 26 | + type Error = GlibNoneError; |
| 27 | + #[inline] |
| 28 | + unsafe fn try_from_glib(val: libc::c_ulong) -> Result<Self, GlibNoneError> { |
| 29 | + NonZeroU64::new(val as u64).map(Self).ok_or(GlibNoneError) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +pub trait CancellableExtManual { |
| 34 | + // rustdoc-stripper-ignore-next |
| 35 | + /// Convenience function to connect to the `signal::Cancellable::cancelled` signal. Also |
| 36 | + /// handles the race condition that may happen if the cancellable is cancelled right before |
| 37 | + /// connecting. If the operation is cancelled from another thread, `callback` will be called |
| 38 | + /// in the thread that cancelled the operation, not the thread that is running the operation. |
| 39 | + /// This may be the main thread, so the callback should not do something that can block. |
| 40 | + /// |
| 41 | + /// `callback` is called at most once, either directly at the time of the connect if `self` is |
| 42 | + /// already cancelled, or when `self` is cancelled in some thread. |
| 43 | + /// |
| 44 | + /// Since GLib 2.40, the lock protecting `self` is not held when `callback` is invoked. This |
| 45 | + /// lifts a restriction in place for earlier GLib versions which now makes it easier to write |
| 46 | + /// cleanup code that unconditionally invokes e.g. |
| 47 | + /// [`CancellableExt::cancel()`][crate::prelude::CancellableExt::cancel()]. |
| 48 | + /// |
| 49 | + /// # Returns |
| 50 | + /// |
| 51 | + /// The id of the signal handler or `None` if `self` has already been cancelled. |
| 52 | + #[doc(alias = "g_cancellable_connect")] |
| 53 | + fn connect_cancelled<F: FnOnce(&Self) + Send + 'static>( |
| 54 | + &self, |
| 55 | + callback: F, |
| 56 | + ) -> Option<CancelledHandlerId>; |
| 57 | + // rustdoc-stripper-ignore-next |
| 58 | + /// Disconnects a handler from a cancellable instance. Additionally, in the event that a signal |
| 59 | + /// handler is currently running, this call will block until the handler has finished. Calling |
| 60 | + /// this function from a callback registered with [`Self::connect_cancelled`] will therefore |
| 61 | + /// result in a deadlock. |
| 62 | + /// |
| 63 | + /// This avoids a race condition where a thread cancels at the same time as the cancellable |
| 64 | + /// operation is finished and the signal handler is removed. |
| 65 | + #[doc(alias = "g_cancellable_disconnect")] |
| 66 | + fn disconnect_cancelled(&self, id: CancelledHandlerId); |
| 67 | + // rustdoc-stripper-ignore-next |
| 68 | + /// Returns a `Future` that completes when the cancellable becomes cancelled. Completes |
| 69 | + /// immediately if the cancellable is already cancelled. |
| 70 | + fn future(&self) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>; |
| 71 | +} |
| 72 | + |
| 73 | +impl<O: IsA<Cancellable>> CancellableExtManual for O { |
| 74 | + #[doc(alias = "g_cancellable_connect")] |
| 75 | + fn connect_cancelled<F: FnOnce(&Self) + Send + 'static>( |
| 76 | + &self, |
| 77 | + callback: F, |
| 78 | + ) -> Option<CancelledHandlerId> { |
| 79 | + unsafe extern "C" fn connect_trampoline<P: IsA<Cancellable>, F: FnOnce(&P)>( |
| 80 | + this: *mut ffi::GCancellable, |
| 81 | + callback: glib::ffi::gpointer, |
| 82 | + ) { |
| 83 | + let callback: &mut Option<F> = &mut *(callback as *mut Option<F>); |
| 84 | + let callback = callback |
| 85 | + .take() |
| 86 | + .expect("Cancellable::cancel() closure called multiple times"); |
| 87 | + callback(Cancellable::from_glib_borrow(this).unsafe_cast_ref()) |
| 88 | + } |
| 89 | + |
| 90 | + unsafe extern "C" fn destroy_closure<F>(ptr: glib::ffi::gpointer) { |
| 91 | + Box::<Option<F>>::from_raw(ptr as *mut _); |
| 92 | + } |
| 93 | + |
| 94 | + let callback: Box<Option<F>> = Box::new(Some(callback)); |
| 95 | + unsafe { |
| 96 | + from_glib(ffi::g_cancellable_connect( |
| 97 | + self.as_ptr() as *mut _, |
| 98 | + Some(std::mem::transmute::<_, unsafe extern "C" fn()>( |
| 99 | + connect_trampoline::<Self, F> as *const (), |
| 100 | + )), |
| 101 | + Box::into_raw(callback) as *mut _, |
| 102 | + Some(destroy_closure::<F>), |
| 103 | + )) |
| 104 | + } |
| 105 | + } |
| 106 | + #[doc(alias = "g_cancellable_disconnect")] |
| 107 | + fn disconnect_cancelled(&self, id: CancelledHandlerId) { |
| 108 | + unsafe { ffi::g_cancellable_disconnect(self.as_ptr() as *mut _, id.as_raw()) }; |
| 109 | + } |
| 110 | + fn future(&self) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>> { |
| 111 | + let cancellable = self.as_ref().clone(); |
| 112 | + let (tx, rx) = oneshot::channel(); |
| 113 | + let id = cancellable.connect_cancelled(move |_| { |
| 114 | + let _ = tx.send(()); |
| 115 | + }); |
| 116 | + Box::pin(async move { |
| 117 | + rx.await.unwrap(); |
| 118 | + if let Some(id) = id { |
| 119 | + cancellable.disconnect_cancelled(id); |
| 120 | + } |
| 121 | + }) |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +#[cfg(test)] |
| 126 | +mod tests { |
| 127 | + use super::*; |
| 128 | + |
| 129 | + #[test] |
| 130 | + fn cancellable_callback() { |
| 131 | + let c = Cancellable::new(); |
| 132 | + let id = c.connect_cancelled(|_| {}); |
| 133 | + c.cancel(); // if it doesn't crash at this point, then we're good to go! |
| 134 | + c.disconnect_cancelled(id.unwrap()); |
| 135 | + } |
| 136 | + |
| 137 | + #[test] |
| 138 | + fn cancellable_future() { |
| 139 | + let c = Cancellable::new(); |
| 140 | + c.cancel(); |
| 141 | + glib::MainContext::new().block_on(c.future()); |
| 142 | + } |
| 143 | + |
| 144 | + #[test] |
| 145 | + fn cancellable_future_thread() { |
| 146 | + let cancellable = Cancellable::new(); |
| 147 | + let c = cancellable.clone(); |
| 148 | + std::thread::spawn(move || c.cancel()).join().unwrap(); |
| 149 | + glib::MainContext::new().block_on(cancellable.future()); |
| 150 | + } |
| 151 | + |
| 152 | + #[test] |
| 153 | + fn cancellable_future_delayed() { |
| 154 | + let ctx = glib::MainContext::new(); |
| 155 | + let c = Cancellable::new(); |
| 156 | + let (tx, rx) = oneshot::channel(); |
| 157 | + { |
| 158 | + let c = c.clone(); |
| 159 | + ctx.spawn_local(async move { |
| 160 | + c.future().await; |
| 161 | + tx.send(()).unwrap(); |
| 162 | + }); |
| 163 | + } |
| 164 | + std::thread::spawn(move || c.cancel()).join().unwrap(); |
| 165 | + ctx.block_on(rx).unwrap(); |
| 166 | + } |
10 | 167 | }
|
0 commit comments