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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// Take a look at the license at the top of the repository in the LICENSE file.

// TODO: support marshaller.

use std::mem;
use std::ptr;
use std::slice;

use libc::{c_uint, c_void};

use crate::translate::{from_glib_none, mut_override, ToGlibPtr, ToGlibPtrMut, Uninitialized};
use crate::value::FromValue;
use crate::StaticType;
use crate::ToValue;
use crate::Type;
use crate::Value;

wrapper! {
    #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
    #[doc(alias = "GClosure")]
    pub struct Closure(Shared<gobject_ffi::GClosure>);

    match fn {
        ref => |ptr| {
            gobject_ffi::g_closure_ref(ptr);
            gobject_ffi::g_closure_sink(ptr);
        },
        unref => |ptr| gobject_ffi::g_closure_unref(ptr),
        type_ => || gobject_ffi::g_closure_get_type(),
    }
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub struct RustClosure(Closure);

impl RustClosure {
    // rustdoc-stripper-ignore-next
    /// Creates a new closure around a Rust closure.
    ///
    /// See [`glib::closure!`] for a way to create a closure with concrete types.
    ///
    /// # Panics
    ///
    /// Invoking the closure with wrong argument types or returning the wrong return value type
    /// will panic.
    ///
    /// # Example
    ///
    /// ```
    /// use glib::prelude::*;
    ///
    /// let closure = glib::RustClosure::new(|values| {
    ///     let x = values[0].get::<i32>().unwrap();
    ///     Some((x + 1).to_value())
    /// });
    ///
    /// assert_eq!(
    ///     closure.invoke::<i32>(&[&1i32]),
    ///     2,
    /// );
    /// ```
    #[doc(alias = "g_closure_new")]
    pub fn new<F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static>(callback: F) -> Self {
        Self(Closure::new(callback))
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new closure around a Rust closure.
    ///
    /// See [`glib::closure_local!`] for a way to create a closure with concrete types.
    ///
    /// # Panics
    ///
    /// Invoking the closure with wrong argument types or returning the wrong return value type
    /// will panic.
    ///
    /// Invoking the closure from a different thread than this one will panic.
    #[doc(alias = "g_closure_new")]
    pub fn new_local<F: Fn(&[Value]) -> Option<Value> + 'static>(callback: F) -> Self {
        Self(Closure::new_local(callback))
    }

    // rustdoc-stripper-ignore-next
    /// Invokes the closure with the given arguments.
    ///
    /// For invalidated closures this returns the "default" value of the return type. For nullable
    /// types this is `None`, which means that e.g. requesting `R = String` will panic will `R =
    /// Option<String>` will return `None`.
    ///
    /// # Panics
    ///
    /// The argument types and return value type must match the ones expected by the closure or
    /// otherwise this function panics.
    #[doc(alias = "g_closure_invoke")]
    pub fn invoke<R: TryFromClosureReturnValue>(&self, values: &[&dyn ToValue]) -> R {
        let values = values
            .iter()
            .copied()
            .map(ToValue::to_value)
            .collect::<smallvec::SmallVec<[_; 10]>>();

        R::try_from_closure_return_value(self.invoke_with_values(R::static_type(), &values))
            .expect("Invalid return value")
    }

    // rustdoc-stripper-ignore-next
    /// Invokes the closure with the given arguments.
    ///
    /// For invalidated closures this returns the "default" value of the return type.
    ///
    /// # Panics
    ///
    /// The argument types and return value type must match the ones expected by the closure or
    /// otherwise this function panics.
    #[doc(alias = "g_closure_invoke")]
    pub fn invoke_with_values(&self, return_type: Type, values: &[Value]) -> Option<Value> {
        unsafe { self.0.invoke_with_values(return_type, values) }
    }

    // rustdoc-stripper-ignore-next
    /// Invalidates the closure.
    ///
    /// Invoking an invalidated closure has no effect.
    #[doc(alias = "g_closure_invalidate")]
    pub fn invalidate(&self) {
        self.0.invalidate();
    }
}

impl From<RustClosure> for Closure {
    fn from(c: RustClosure) -> Self {
        c.0
    }
}

impl AsRef<Closure> for RustClosure {
    fn as_ref(&self) -> &Closure {
        &self.0
    }
}

impl AsRef<Closure> for Closure {
    fn as_ref(&self) -> &Closure {
        self
    }
}

impl Closure {
    // rustdoc-stripper-ignore-next
    /// Creates a new closure around a Rust closure.
    ///
    /// Note that [`RustClosure`] provides more convenient and non-unsafe API for invoking
    /// closures. This type mostly exists for FFI interop.
    ///
    /// # Panics
    ///
    /// Invoking the closure with wrong argument types or returning the wrong return value type
    /// will panic.
    ///
    ///
    /// # Example
    ///
    /// ```
    /// use glib::prelude::*;
    ///
    /// let closure = glib::Closure::new(|values| {
    ///     let x = values[0].get::<i32>().unwrap();
    ///     Some((x + 1).to_value())
    /// });
    ///
    /// // Invoking non-Rust closures is unsafe because of possibly missing
    /// // argument and return value type checks.
    /// let res = unsafe {
    ///     closure
    ///         .invoke_with_values(glib::Type::I32, &[1i32.to_value()])
    ///         .and_then(|v| v.get::<i32>().ok())
    ///         .expect("Invalid return value")
    /// };
    ///
    /// assert_eq!(res, 2);
    /// ```
    #[doc(alias = "g_closure_new")]
    pub fn new<F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static>(callback: F) -> Self {
        unsafe { Self::new_unsafe(callback) }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new closure around a Rust closure.
    ///
    /// Note that [`RustClosure`] provides more convenient and non-unsafe API for invoking
    /// closures. This type mostly exists for FFI interop.
    ///
    /// # Panics
    ///
    /// Invoking the closure with wrong argument types or returning the wrong return value type
    /// will panic.
    ///
    /// Invoking the closure from a different thread than this one will panic.
    #[doc(alias = "g_closure_new")]
    pub fn new_local<F: Fn(&[Value]) -> Option<Value> + 'static>(callback: F) -> Self {
        let callback = crate::thread_guard::ThreadGuard::new(callback);

        unsafe { Self::new_unsafe(move |values| (callback.get_ref())(values)) }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new closure around a Rust closure.
    ///
    /// # Safety
    ///
    /// The captured variables of the closure must stay valid as long as the return value of this
    /// constructor does, and it must be valid to call the closure from any thread that is used by
    /// callers.
    #[doc(alias = "g_closure_new")]
    pub unsafe fn new_unsafe<F: Fn(&[Value]) -> Option<Value>>(callback: F) -> Self {
        unsafe extern "C" fn marshal<F>(
            _closure: *mut gobject_ffi::GClosure,
            return_value: *mut gobject_ffi::GValue,
            n_param_values: c_uint,
            param_values: *const gobject_ffi::GValue,
            _invocation_hint: *mut c_void,
            marshal_data: *mut c_void,
        ) where
            F: Fn(&[Value]) -> Option<Value>,
        {
            let values = if n_param_values == 0 {
                &[]
            } else {
                slice::from_raw_parts(param_values as *const _, n_param_values as usize)
            };
            let callback: &F = &*(marshal_data as *mut _);
            let result = callback(values);

            if return_value.is_null() {
                assert!(
                    result.is_none(),
                    "Closure returned a return value but the caller did not expect one"
                );
            } else {
                let return_value = &mut *(return_value as *mut Value);
                match result {
                    Some(result) => {
                        assert!(
                            result.type_().is_a(return_value.type_()),
                            "Closure returned a value of type {} but caller expected {}",
                            result.type_(),
                            return_value.type_()
                        );
                        *return_value = result;
                    }
                    None if return_value.type_() == Type::INVALID => (),
                    None => {
                        panic!(
                            "Closure returned no value but the caller expected a value of type {}",
                            return_value.type_()
                        );
                    }
                }
            }
        }

        unsafe extern "C" fn finalize<F>(
            notify_data: *mut c_void,
            _closure: *mut gobject_ffi::GClosure,
        ) where
            F: Fn(&[Value]) -> Option<Value>,
        {
            let _callback: Box<F> = Box::from_raw(notify_data as *mut _);
            // callback is dropped here.
        }

        // Due to bitfields we have to do our own calculations here for the size of the GClosure:
        // - 4: 32 bits in guint bitfields at the beginning
        // - padding due to alignment needed for the following pointer
        // - 3 * size_of<*mut c_void>: 3 pointers
        // We don't store any custom data ourselves in the GClosure
        let size = u32::max(4, mem::align_of::<*mut c_void>() as u32)
            + 3 * mem::size_of::<*mut c_void>() as u32;
        let closure = gobject_ffi::g_closure_new_simple(size, ptr::null_mut());
        assert_ne!(closure, ptr::null_mut());
        let callback = Box::new(callback);
        let ptr: *mut F = Box::into_raw(callback);
        let ptr: *mut c_void = ptr as *mut _;
        gobject_ffi::g_closure_set_meta_marshal(closure, ptr, Some(marshal::<F>));
        gobject_ffi::g_closure_add_finalize_notifier(closure, ptr, Some(finalize::<F>));
        from_glib_none(closure)
    }

    // rustdoc-stripper-ignore-next
    /// Invokes the closure with the given arguments.
    ///
    /// For invalidated closures this returns the "default" value of the return type.
    ///
    /// # Safety
    ///
    /// The argument types and return value type must match the ones expected by the closure or
    /// otherwise the behaviour is undefined.
    ///
    /// Closures created from Rust via e.g. [`Closure::new`] will panic on type mismatches but
    /// this is not guaranteed for closures created from other languages.
    #[doc(alias = "g_closure_invoke")]
    pub unsafe fn invoke_with_values(&self, return_type: Type, values: &[Value]) -> Option<Value> {
        let mut result = if return_type == Type::UNIT {
            Value::uninitialized()
        } else {
            Value::from_type(return_type)
        };
        let result_ptr = if return_type == Type::UNIT {
            ptr::null_mut()
        } else {
            result.to_glib_none_mut().0
        };

        gobject_ffi::g_closure_invoke(
            self.to_glib_none().0 as *mut _,
            result_ptr,
            values.len() as u32,
            mut_override(values.as_ptr()) as *mut gobject_ffi::GValue,
            ptr::null_mut(),
        );

        if return_type == Type::UNIT {
            None
        } else {
            Some(result)
        }
    }

    // rustdoc-stripper-ignore-next
    /// Invalidates the closure.
    ///
    /// Invoking an invalidated closure has no effect.
    #[doc(alias = "g_closure_invalidate")]
    pub fn invalidate(&self) {
        unsafe {
            gobject_ffi::g_closure_invalidate(self.to_glib_none().0);
        }
    }
}

pub trait ToClosureReturnValue {
    fn to_closure_return_value(&self) -> Option<Value>;
}

impl ToClosureReturnValue for () {
    fn to_closure_return_value(&self) -> Option<Value> {
        None
    }
}

impl<T: ToValue> ToClosureReturnValue for T {
    fn to_closure_return_value(&self) -> Option<Value> {
        Some(self.to_value())
    }
}

pub trait TryFromClosureReturnValue: StaticType + Sized + 'static {
    fn try_from_closure_return_value(v: Option<Value>) -> Result<Self, crate::BoolError>;
}

impl TryFromClosureReturnValue for () {
    fn try_from_closure_return_value(v: Option<Value>) -> Result<Self, crate::BoolError> {
        match v {
            None => Ok(()),
            Some(v) => Err(bool_error!(
                "Invalid return value: expected (), got {}",
                v.type_()
            )),
        }
    }
}

impl<T: for<'a> FromValue<'a> + StaticType + 'static> TryFromClosureReturnValue for T {
    fn try_from_closure_return_value(v: Option<Value>) -> Result<Self, crate::BoolError> {
        v.ok_or_else(|| {
            bool_error!(
                "Invalid return value: expected {}, got ()",
                T::static_type()
            )
        })
        .and_then(|v| {
            v.get_owned::<T>().map_err(|_| {
                bool_error!(
                    "Invalid return value: expected {}, got {}",
                    T::static_type(),
                    v.type_()
                )
            })
        })
    }
}

unsafe impl Send for Closure {}
unsafe impl Sync for Closure {}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    use super::*;

    #[allow(clippy::unnecessary_wraps)]
    fn closure_fn(values: &[Value]) -> Option<Value> {
        assert_eq!(values.len(), 2);
        let string_arg = values[0].get::<&str>();
        assert_eq!(string_arg, Ok("test"));
        let int_arg = values[1].get::<i32>();
        assert_eq!(int_arg, Ok(42));
        Some(24.to_value())
    }

    #[test]
    fn test_closure() {
        let call_count = Arc::new(AtomicUsize::new(0));

        let count = call_count.clone();
        let closure = RustClosure::new(move |values| {
            count.fetch_add(1, Ordering::Relaxed);
            assert_eq!(values.len(), 2);
            let string_arg = values[0].get::<&str>();
            assert_eq!(string_arg, Ok("test"));
            let int_arg = values[1].get::<i32>();
            assert_eq!(int_arg, Ok(42));
            None
        });
        closure.invoke::<()>(&[&"test", &42]);
        assert_eq!(call_count.load(Ordering::Relaxed), 1);

        closure.invoke::<()>(&[&"test", &42]);
        assert_eq!(call_count.load(Ordering::Relaxed), 2);

        closure.invalidate();
        closure.invoke::<()>(&[&"test", &42]);
        assert_eq!(call_count.load(Ordering::Relaxed), 2);

        let closure = RustClosure::new(closure_fn);
        let result = closure.invoke::<i32>(&[&"test", &42]);
        assert_eq!(result, 24);
        closure.invalidate();
        let result = closure.invoke::<i32>(&[&"test", &42]);
        assert_eq!(result, 0);
    }
}