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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// 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 {
    /// Creates a [`Task`][crate::Task] acting on `source_object`, which will eventually be
    /// used to invoke `callback` in the current
    /// [thread-default main context][g-main-context-push-thread-default].
    ///
    /// Call this in the "start" method of your asynchronous method, and
    /// pass the [`Task`][crate::Task] around throughout the asynchronous operation. You
    /// can use `g_task_set_task_data()` to attach task-specific data to the
    /// object, which you can retrieve later via `g_task_get_task_data()`.
    ///
    /// By default, if `cancellable` is cancelled, then the return value of
    /// the task will always be [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled], even if the task had
    /// already completed before the cancellation. This allows for
    /// simplified handling in cases where cancellation may imply that
    /// other objects that the task depends on have been destroyed. If you
    /// do not want this behavior, you can use
    /// [`set_check_cancellable()`][Self::set_check_cancellable()] to change it.
    /// ## `source_object`
    /// the [`glib::Object`][crate::glib::Object] that owns
    ///  this task, or [`None`].
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] object, [`None`] to ignore.
    /// ## `callback`
    /// a `GAsyncReadyCallback`.
    /// ## `callback_data`
    /// user data passed to `callback`.
    ///
    /// # Returns
    ///
    /// a [`Task`][crate::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 _,
            ))
        }
    }

    /// Sets `self`'s result to `error` (which `self` assumes ownership of)
    /// and completes the task (see `g_task_return_pointer()` for more
    /// discussion of exactly what this means).
    ///
    /// Note that since the task takes ownership of `error`, and since the
    /// task may be completed before returning from [`return_error()`][Self::return_error()],
    /// you cannot assume that `error` is still valid after calling this.
    /// Call `g_error_copy()` on the error if you need to keep a local copy
    /// as well.
    ///
    /// See also `g_task_return_new_error()`.
    /// ## `error`
    /// the [`glib::Error`][crate::glib::Error] result of a task function.
    #[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 _);
        }
    }

    /// Gets `self`'s priority
    ///
    /// # Returns
    ///
    /// `self`'s priority
    #[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)) }
    }

    /// Sets `self`'s priority. If you do not call this, it will default to
    /// `G_PRIORITY_DEFAULT`.
    ///
    /// This will affect the priority of `GSources` created with
    /// `g_task_attach_source()` and the scheduling of tasks run in threads,
    /// and can also be explicitly retrieved later via
    /// [`priority()`][Self::priority()].
    /// ## `priority`
    /// the [priority][io-priority] of the request
    #[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());
        }
    }

    /// Sets `self`'s result to `result` (by copying it) and completes the task.
    ///
    /// If `result` is [`None`] then a [`glib::Value`][crate::glib::Value] of type `G_TYPE_POINTER`
    /// with a value of [`None`] will be used for the result.
    ///
    /// This is a very generic low-level method intended primarily for use
    /// by language bindings; for C code, `g_task_return_pointer()` and the
    /// like will normally be much easier to use.
    /// ## `result`
    /// the [`glib::Value`][crate::glib::Value] result of
    ///  a task function
    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),
            )
        }
    }

    /// Gets the result of `self` as a [`glib::Value`][crate::glib::Value], and transfers ownership of
    /// that value to the caller. As with [`return_value()`][Self::return_value()], this is
    /// a generic low-level method; `g_task_propagate_pointer()` and the like
    /// will usually be more useful for C code.
    ///
    /// If the task resulted in an error, or was cancelled, then this will
    /// instead set `error` and return [`false`].
    ///
    /// Since this method transfers ownership of the return value (or
    /// error) to the caller, you may only call it once.
    ///
    /// # Returns
    ///
    /// [`true`] if `self` succeeded, [`false`] on error.
    ///
    /// ## `value`
    /// return location for the [`glib::Value`][crate::glib::Value]
    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!(),
        }
    }
}