1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use crate::SaveDelegate;
use futures_core::future::Future;
use glib::{signal::connect_raw, translate::*, Cast, IsA, SignalHandlerId};
use std::mem::transmute;

pub trait SaveDelegateExtManual {
    fn connect_save<F, R>(&self, f: F) -> SignalHandlerId
    where
        F: Fn(&Self) -> R + 'static,
        R: Future<Output = Result<(), glib::Error>> + 'static;
}

impl<O: IsA<SaveDelegate>> SaveDelegateExtManual for O {
    fn connect_save<F, R>(&self, f: F) -> SignalHandlerId
    where
        F: Fn(&Self) -> R + 'static,
        R: Future<Output = Result<(), glib::Error>> + 'static,
    {
        unsafe extern "C" fn save_trampoline<
            P: IsA<SaveDelegate>,
            F: Fn(&P) -> R + 'static,
            R: Future<Output = Result<(), glib::Error>> + 'static,
        >(
            this: *mut ffi::PanelSaveDelegate,
            task: *mut gio::ffi::GTask,
            f: glib::ffi::gpointer,
        ) -> glib::ffi::gboolean {
            let f: &F = &*(f as *const F);
            let task: gio::Task<bool> = from_glib_none(task);
            let delegate = SaveDelegate::from_glib_borrow(this);
            let fut = f(delegate.unsafe_cast_ref());
            task.context().spawn_local(async move {
                task.return_result(fut.await.map(|_| true));
            });
            true.into_glib()
        }
        unsafe {
            let f: Box<F> = Box::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"save\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    save_trampoline::<Self, F, R> as *const (),
                )),
                Box::into_raw(f),
            )
        }
    }
}