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
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::AsyncResult;
use crate::Cancellable;
use crate::Task;
use glib::object::IsA;
use glib::translate::*;
use libc::c_void;
use std::boxed::Box as Box_;
use std::ptr;

impl Task {
    #[doc(alias = "g_task_new")]
    pub fn new<P: IsA<Cancellable>, Q: FnOnce(&AsyncResult, Option<&glib::Object>) + 'static>(
        source_object: Option<&glib::Object>,
        cancellable: Option<&P>,
        callback: Q,
    ) -> Task {
        let callback_data = Box_::new(callback);
        unsafe extern "C" fn trampoline<
            Q: FnOnce(&AsyncResult, Option<&glib::Object>) + 'static,
        >(
            source_object: *mut glib::gobject_ffi::GObject,
            res: *mut ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let source_object = Option::<glib::Object>::from_glib_borrow(source_object);
            let res = AsyncResult::from_glib_borrow(res);
            let callback: Box_<Q> = Box::from_raw(user_data as *mut _);
            callback(&res, source_object.as_ref().as_ref());
        }
        let callback = trampoline::<Q>;
        unsafe {
            from_glib_full(ffi::g_task_new(
                source_object.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(callback_data) as *mut _,
            ))
        }
    }

    #[doc(alias = "g_task_return_error")]
    pub fn return_error(&self, error: glib::Error) {
        unsafe {
            ffi::g_task_return_error(self.to_glib_none().0, error.to_glib_full() as *mut _);
        }
    }

    #[doc(alias = "get_priority")]
    #[doc(alias = "g_task_get_priority")]
    pub fn priority(&self) -> glib::source::Priority {
        unsafe { FromGlib::from_glib(ffi::g_task_get_priority(self.to_glib_none().0)) }
    }

    #[doc(alias = "g_task_set_priority")]
    pub fn set_priority(&self, priority: glib::source::Priority) {
        unsafe {
            ffi::g_task_set_priority(self.to_glib_none().0, priority.into_glib());
        }
    }

    pub fn return_value(&self, result: &glib::Value) {
        unsafe extern "C" fn value_free(value: *mut c_void) {
            glib::gobject_ffi::g_value_unset(value as *mut glib::gobject_ffi::GValue);
            glib::ffi::g_free(value);
        }
        unsafe {
            let value: *mut glib::gobject_ffi::GValue =
                <&glib::Value>::to_glib_full_from_slice(&[result]);
            ffi::g_task_return_pointer(
                self.to_glib_none().0,
                value as *mut c_void,
                Some(value_free),
            )
        }
    }

    pub fn propagate_value(&self) -> Result<glib::Value, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let value = ffi::g_task_propagate_pointer(self.to_glib_none().0, &mut error);
            if !error.is_null() {
                return Err(from_glib_full(error));
            }
            let value = from_glib_full(value as *mut glib::gobject_ffi::GValue);
            match value {
                Some(value) => Ok(value),
                None => Ok(glib::Value::from_type(glib::types::Type::UNIT)),
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::prelude::*;
    use crate::test_util::run_async_local;

    #[test]
    fn test_int_async_result() {
        match run_async_local(|tx, l| {
            let c = crate::Cancellable::new();
            let t = crate::Task::new(
                None,
                Some(&c),
                move |a: &AsyncResult, _b: Option<&glib::Object>| {
                    let t = a.downcast_ref::<crate::Task>().unwrap();
                    tx.send(t.propagate_value()).unwrap();
                    l.quit();
                },
            );
            t.return_value(&100_i32.to_value());
        }) {
            Err(_) => panic!(),
            Ok(i) => {
                assert!(i.get::<i32>().unwrap() == 100);
            }
        }
    }

    #[test]
    fn test_object_async_result() {
        use glib::subclass::prelude::*;
        pub struct MySimpleObjectPrivate {
            pub size: std::cell::RefCell<Option<i64>>,
        }

        #[glib::object_subclass]
        impl ObjectSubclass for MySimpleObjectPrivate {
            const NAME: &'static str = "MySimpleObjectPrivate";
            type ParentType = glib::Object;
            type Type = MySimpleObject;

            fn new() -> Self {
                Self {
                    size: std::cell::RefCell::new(Some(100)),
                }
            }
        }

        impl ObjectImpl for MySimpleObjectPrivate {}

        glib::wrapper! {
            pub struct MySimpleObject(ObjectSubclass<MySimpleObjectPrivate>);
        }

        impl MySimpleObject {
            pub fn new() -> Self {
                glib::Object::new(&[]).expect("Failed to create MySimpleObject")
            }

            #[doc(alias = "get_size")]
            pub fn size(&self) -> Option<i64> {
                let imp = MySimpleObjectPrivate::from_instance(self);
                *imp.size.borrow()
            }

            pub fn set_size(&self, size: i64) {
                let imp = MySimpleObjectPrivate::from_instance(self);
                imp.size.borrow_mut().replace(size);
            }
        }

        impl Default for MySimpleObject {
            fn default() -> Self {
                Self::new()
            }
        }

        match run_async_local(|tx, l| {
            let c = crate::Cancellable::new();
            let t = crate::Task::new(
                None,
                Some(&c),
                move |a: &AsyncResult, _b: Option<&glib::Object>| {
                    let t = a.downcast_ref::<crate::Task>().unwrap();
                    tx.send(t.propagate_value()).unwrap();
                    l.quit();
                },
            );
            let my_object = MySimpleObject::new();
            my_object.set_size(100);
            t.return_value(&my_object.upcast::<glib::Object>().to_value());
        }) {
            Err(_) => panic!(),
            Ok(o) => {
                let o = o
                    .get::<glib::Object>()
                    .unwrap()
                    .downcast::<MySimpleObject>()
                    .unwrap();

                assert!(o.size() == Some(100));
            }
        }
    }

    #[test]
    fn test_error() {
        match run_async_local(|tx, l| {
            let c = crate::Cancellable::new();
            let t = crate::Task::new(
                None,
                Some(&c),
                move |a: &AsyncResult, _b: Option<&glib::Object>| {
                    let t = a.downcast_ref::<crate::Task>().unwrap();
                    tx.send(t.propagate_value()).unwrap();
                    l.quit();
                },
            );
            t.return_error(glib::Error::new(
                crate::IOErrorEnum::WouldBlock,
                "WouldBlock",
            ));
        }) {
            Err(e) => match e.kind().unwrap() {
                crate::IOErrorEnum::WouldBlock => {}
                _ => panic!(),
            },
            Ok(_) => panic!(),
        }
    }

    #[test]
    fn test_cancelled() {
        match run_async_local(|tx, l| {
            let c = crate::Cancellable::new();
            let t = crate::Task::new(
                None,
                Some(&c),
                move |a: &AsyncResult, _b: Option<&glib::Object>| {
                    let t = a.downcast_ref::<crate::Task>().unwrap();
                    tx.send(t.propagate_value()).unwrap();
                    l.quit();
                },
            );
            c.cancel();
            t.return_error_if_cancelled();
        }) {
            Err(e) => match e.kind().unwrap() {
                crate::IOErrorEnum::Cancelled => {}
                _ => panic!(),
            },
            Ok(_) => panic!(),
        }
    }
}