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
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::Expression;
use glib::translate::*;
use glib::{value::ValueType, StaticType, Value};

glib::wrapper! {
    /// An expression using a custom `GClosure` to compute the value from
    /// its parameters.
    #[derive(Debug)]
    #[doc(alias = "GtkClosureExpression")]
    pub struct ClosureExpression(Shared<ffi::GtkClosureExpression>);

    match fn {
        ref => |ptr| ffi::gtk_expression_ref(ptr as *mut ffi::GtkExpression),
        unref => |ptr| ffi::gtk_expression_unref(ptr as *mut ffi::GtkExpression),
    }
}

define_expression!(
    ClosureExpression,
    ffi::GtkClosureExpression,
    ffi::gtk_closure_expression_get_type
);

impl ClosureExpression {
    /// Creates a [`Expression`][crate::Expression] that calls `closure` when it is evaluated.
    /// `closure` is called with the `this` object and the results of evaluating
    /// the `params` expressions.
    /// ## `value_type`
    /// the type of the value that this expression evaluates to
    /// ## `closure`
    /// closure to call when evaluating this expression. If closure is floating, it is adopted
    /// ## `params`
    /// expressions for each parameter
    ///
    /// # Returns
    ///
    /// a new [`Expression`][crate::Expression]
    #[doc(alias = "gtk_closure_expression_new")]
    pub fn new<F, R>(callback: F, params: &[Expression]) -> Self
    where
        F: Fn(&[Value]) -> R + 'static,
        R: ValueType,
    {
        assert_initialized_main_thread!();
        let closure = glib::Closure::new_local(move |values| {
            let ret = callback(values);
            Some(ret.to_value())
        });
        unsafe {
            from_glib_full(ffi::gtk_closure_expression_new(
                R::Type::static_type().into_glib(),
                closure.to_glib_none().0,
                params.len() as u32,
                params.to_glib_full(),
            ))
        }
    }

    #[doc(alias = "gtk_closure_expression_new")]
    pub fn with_closure<R>(closure: glib::Closure, params: &[Expression]) -> Self
    where
        R: ValueType,
    {
        assert_initialized_main_thread!();
        unsafe {
            from_glib_full(ffi::gtk_closure_expression_new(
                R::Type::static_type().into_glib(),
                closure.to_glib_none().0,
                params.len() as u32,
                params.to_glib_full(),
            ))
        }
    }
}