gtk4/
closure_expression.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use glib::{translate::*, Value};
4
5use crate::{ffi, prelude::*, ClosureExpression, Expression};
6
7define_expression!(ClosureExpression, ffi::GtkClosureExpression);
8
9impl ClosureExpression {
10    /// Creates a [`Expression`][crate::Expression] that calls `closure` when it is evaluated.
11    ///
12    /// `closure` is called with the `this` object and the results of evaluating
13    /// the `params` expressions.
14    /// ## `value_type`
15    /// the type of the value that this expression evaluates to
16    /// ## `closure`
17    /// closure to call when evaluating this expression. If closure is floating, it is adopted
18    /// ## `params`
19    /// expressions for each parameter
20    ///
21    /// # Returns
22    ///
23    /// a new [`Expression`][crate::Expression]
24    #[doc(alias = "gtk_closure_expression_new")]
25    pub fn new<R>(
26        params: impl IntoIterator<Item = impl AsRef<Expression>>,
27        closure: glib::RustClosure,
28    ) -> Self
29    where
30        R: ValueType,
31    {
32        assert_initialized_main_thread!();
33
34        let params = params
35            .into_iter()
36            .map(|e| e.as_ref().clone())
37            .collect::<Vec<_>>();
38
39        unsafe {
40            from_glib_full(ffi::gtk_closure_expression_new(
41                R::Type::static_type().into_glib(),
42                closure.as_ref().to_glib_none().0,
43                params.len() as u32,
44                params.to_glib_full(),
45            ))
46        }
47    }
48
49    #[doc(alias = "gtk_closure_expression_new")]
50    pub fn with_callback<R, F>(
51        params: impl IntoIterator<Item = impl AsRef<Expression>>,
52        callback: F,
53    ) -> Self
54    where
55        F: Fn(&[Value]) -> R + 'static,
56        R: ValueType,
57    {
58        assert_initialized_main_thread!();
59        let closure = glib::Closure::new_local(move |values| {
60            let ret = callback(values);
61            Some(ret.to_value())
62        });
63
64        let params = params
65            .into_iter()
66            .map(|e| e.as_ref().clone())
67            .collect::<Vec<_>>();
68
69        unsafe {
70            from_glib_full(ffi::gtk_closure_expression_new(
71                R::Type::static_type().into_glib(),
72                closure.to_glib_none().0,
73                params.len() as u32,
74                params.to_glib_full(),
75            ))
76        }
77    }
78}