gtk4/
expression.rs

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.

use glib::{translate::*, value::FromValue, Object, Type, Value};

use crate::{ffi, prelude::*, Expression};

#[doc(hidden)]
impl AsRef<Expression> for Expression {
    #[inline]
    fn as_ref(&self) -> &Expression {
        self
    }
}

// rustdoc-stripper-ignore-next
/// A common trait implemented by the various [`Expression`](crate::Expression)
/// types.
///
/// # Safety
///
/// The user is not supposed to implement this trait.
pub unsafe trait IsExpression:
    StaticType + FromGlibPtrFull<*mut ffi::GtkExpression> + 'static
{
}

impl Expression {
    #[inline]
    pub fn upcast(self) -> Self {
        self
    }

    #[inline]
    pub fn upcast_ref(&self) -> &Self {
        self
    }

    #[inline]
    pub fn is<E: IsExpression>(&self) -> bool {
        self.type_().is_a(E::static_type())
    }

    #[inline]
    pub fn downcast<E: IsExpression>(self) -> Result<E, Expression> {
        unsafe {
            if self.is::<E>() {
                Ok(from_glib_full(self.into_glib_ptr()))
            } else {
                Err(self)
            }
        }
    }

    #[inline]
    pub fn downcast_ref<E: IsExpression>(&self) -> Option<&E> {
        unsafe {
            if self.is::<E>() {
                Some(&*(self as *const Expression as *const E))
            } else {
                None
            }
        }
    }

    #[inline]
    pub fn type_(&self) -> Type {
        unsafe {
            let ptr = self.as_ptr();
            from_glib((*(*(ptr as *mut glib::gobject_ffi::GTypeInstance)).g_class).g_type)
        }
    }

    #[doc(alias = "gtk_expression_evaluate")]
    pub fn evaluate(&self, this: Option<&impl IsA<Object>>) -> Option<Value> {
        assert_initialized_main_thread!();
        unsafe {
            let mut value = Value::uninitialized();
            let ret = ffi::gtk_expression_evaluate(
                self.to_glib_none().0,
                this.map(|t| t.as_ref()).to_glib_none().0,
                value.to_glib_none_mut().0,
            );
            if from_glib(ret) {
                Some(value)
            } else {
                None
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Similar to [`Self::evaluate`] but panics if the value is of a different
    /// type.
    #[doc(alias = "gtk_expression_evaluate")]
    pub fn evaluate_as<V: for<'b> FromValue<'b> + 'static, T: IsA<Object>>(
        &self,
        this: Option<&T>,
    ) -> Option<V> {
        self.evaluate(this).map(|v| {
            v.get_owned::<V>()
                .expect("Failed to evaluate to this value type")
        })
    }

    // rustdoc-stripper-ignore-next
    /// Create a [`PropertyExpression`](crate::PropertyExpression) that looks up
    /// for `property_name` with self as parameter. This is useful in long
    /// chains of [`Expression`](crate::Expression)s.
    pub fn chain_property<T: IsA<glib::Object>>(
        &self,
        property_name: &str,
    ) -> crate::PropertyExpression {
        crate::PropertyExpression::new(T::static_type(), Some(self), property_name)
    }

    // rustdoc-stripper-ignore-next
    /// Create a [`ClosureExpression`](crate::ClosureExpression) from a
    /// [`glib::Closure`] with self as the second parameter and `R` as the
    /// return type. The return type is checked at run-time and must always
    /// be specified. This is useful in long chains of
    /// [`Expression`](crate::Expression)s when using the [`glib::closure!`]
    /// macro.
    ///
    /// Note that the first parameter will always be the `this` object bound to
    /// the expression. If `None` is passed as `this` then the type of the
    /// first parameter must be `Option<glib::Object>` otherwise type
    /// checking will panic.
    ///
    /// ```no_run
    /// # use gtk4 as gtk;
    /// use glib::{closure, Object};
    /// use gtk::{glib, prelude::*};
    ///
    /// let button = gtk::Button::new();
    /// button.set_label("Hello");
    /// let label = button
    ///     .property_expression("label")
    ///     .chain_closure::<String>(closure!(|_: Option<Object>, label: &str| {
    ///         format!("{} World", label)
    ///     }))
    ///     .evaluate_as::<String, _>(gtk::Widget::NONE);
    /// assert_eq!(label.unwrap(), "Hello World");
    /// ```
    pub fn chain_closure<R>(&self, closure: glib::RustClosure) -> crate::ClosureExpression
    where
        R: glib::value::ValueType,
    {
        crate::ClosureExpression::new::<R>([self], closure)
    }

    // rustdoc-stripper-ignore-next
    /// Create a [`ClosureExpression`](crate::ClosureExpression) with self as
    /// the second parameter. This is useful in long chains of
    /// [`Expression`](crate::Expression)s.
    pub fn chain_closure_with_callback<F, R>(&self, f: F) -> crate::ClosureExpression
    where
        F: Fn(&[glib::Value]) -> R + 'static,
        R: glib::value::ValueType,
    {
        crate::ClosureExpression::with_callback([self], f)
    }
}

impl std::fmt::Debug for Expression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Expression")
            .field("value_type", &self.value_type())
            .field("is_static", &self.is_static())
            .finish()
    }
}

impl glib::value::ValueType for Expression {
    type Type = Self;
}

unsafe impl<'a> glib::value::FromValue<'a> for Expression {
    type Checker = glib::value::GenericValueTypeOrNoneChecker<Self>;

    #[inline]
    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        from_glib_full(crate::ffi::gtk_value_dup_expression(value.to_glib_none().0))
    }
}

impl glib::value::ToValue for Expression {
    #[inline]
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            crate::ffi::gtk_value_set_expression(value.to_glib_none_mut().0, self.to_glib_none().0)
        }
        value
    }

    #[inline]
    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl glib::value::ToValueOptional for Expression {
    fn to_value_optional(s: Option<&Self>) -> glib::Value {
        skip_assert_initialized!();
        let mut value = glib::Value::for_value_type::<Self>();
        unsafe {
            crate::ffi::gtk_value_set_expression(value.to_glib_none_mut().0, s.to_glib_none().0)
        }
        value
    }
}

impl From<Expression> for glib::Value {
    fn from(e: Expression) -> Self {
        skip_assert_initialized!();
        let mut value = glib::Value::for_value_type::<Expression>();
        unsafe {
            crate::ffi::gtk_value_take_expression(value.to_glib_none_mut().0, e.into_glib_ptr())
        }
        value
    }
}

// rustdoc-stripper-ignore-next
/// Trait containing convenience methods in creating
/// [`PropertyExpression`](crate::PropertyExpression) that
/// looks up a property of a [`glib::Object`].
///
/// # Example
///
/// `label_expression` is an [`Expression`](crate::Expression) that looks up at
/// Button's `label` property.
///
/// ```no_run
/// # use gtk4 as gtk;
/// use gtk::prelude::*;
///
/// let button = gtk::Button::new();
/// button.set_label("Label property");
///
/// let label_expression = button.property_expression("label");
/// ```
pub trait GObjectPropertyExpressionExt: IsA<glib::Object> {
    // rustdoc-stripper-ignore-next
    /// Create an expression looking up an object's property.
    fn property_expression(&self, property_name: &str) -> crate::PropertyExpression {
        let obj_expr = crate::ConstantExpression::new(self);
        crate::PropertyExpression::new(Self::static_type(), Some(&obj_expr), property_name)
    }

    // rustdoc-stripper-ignore-next
    /// Create an expression looking up an object's property with a weak
    /// reference.
    fn property_expression_weak(&self, property_name: &str) -> crate::PropertyExpression {
        let obj_expr = crate::ObjectExpression::new(self);
        crate::PropertyExpression::new(Self::static_type(), Some(&obj_expr), property_name)
    }

    // rustdoc-stripper-ignore-next
    /// Create an expression looking up a property in the bound `this` object.
    fn this_expression(property_name: &str) -> crate::PropertyExpression {
        skip_assert_initialized!();
        crate::PropertyExpression::new(Self::static_type(), Expression::NONE, property_name)
    }
}

impl<O: IsA<glib::Object>> GObjectPropertyExpressionExt for O {}

macro_rules! define_expression {
    ($rust_type:ident, $ffi_type:path) => {
        impl std::ops::Deref for $rust_type {
            type Target = crate::Expression;

            #[inline]
            fn deref(&self) -> &Self::Target {
                unsafe { &*(self as *const $rust_type as *const crate::Expression) }
            }
        }

        impl AsRef<crate::Expression> for $rust_type {
            #[inline]
            fn as_ref(&self) -> &crate::Expression {
                self.upcast_ref()
            }
        }

        impl $rust_type {
            #[inline]
            pub fn upcast(self) -> crate::Expression {
                unsafe { std::mem::transmute(self) }
            }

            #[inline]
            pub fn upcast_ref(&self) -> &crate::Expression {
                self
            }
        }

        #[doc(hidden)]
        impl<'a> ToGlibPtr<'a, *const crate::ffi::GtkExpression> for $rust_type {
            type Storage =
                ::std::marker::PhantomData<&'a $crate::glib::shared::Shared<$ffi_type, $rust_type>>;

            #[inline]
            fn to_glib_none(
                &'a self,
            ) -> $crate::glib::translate::Stash<'a, *const crate::ffi::GtkExpression, Self> {
                let stash =
                    $crate::glib::translate::ToGlibPtr::<*const $ffi_type>::to_glib_none(self);
                $crate::glib::translate::Stash(stash.0 as *const _, stash.1)
            }

            #[inline]
            fn to_glib_full(&self) -> *const crate::ffi::GtkExpression {
                $crate::glib::translate::ToGlibPtr::<*const $ffi_type>::to_glib_full(self)
                    as *const _
            }
        }

        #[doc(hidden)]
        impl<'a> ToGlibPtr<'a, *mut crate::ffi::GtkExpression> for $rust_type {
            type Storage =
                ::std::marker::PhantomData<&'a $crate::glib::shared::Shared<$ffi_type, $rust_type>>;

            #[inline]
            fn to_glib_none(
                &'a self,
            ) -> $crate::glib::translate::Stash<'a, *mut crate::ffi::GtkExpression, Self> {
                let stash =
                    $crate::glib::translate::ToGlibPtr::<*mut $ffi_type>::to_glib_none(self);
                $crate::glib::translate::Stash(stash.0 as *mut _, stash.1)
            }

            #[inline]
            fn to_glib_full(&self) -> *mut crate::ffi::GtkExpression {
                $crate::glib::translate::ToGlibPtr::<*mut $ffi_type>::to_glib_full(self) as *mut _
            }
        }

        #[doc(hidden)]
        impl IntoGlibPtr<*mut crate::ffi::GtkExpression> for $rust_type {
            #[inline]
            unsafe fn into_glib_ptr(self) -> *mut crate::ffi::GtkExpression {
                let s = std::mem::ManuallyDrop::new(self);
                s.to_glib_none().0
            }
        }

        #[doc(hidden)]
        impl IntoGlibPtr<*const crate::ffi::GtkExpression> for $rust_type {
            #[inline]
            unsafe fn into_glib_ptr(self) -> *const crate::ffi::GtkExpression {
                let s = std::mem::ManuallyDrop::new(self);
                s.to_glib_none().0
            }
        }

        #[doc(hidden)]
        impl FromGlibPtrFull<*mut crate::ffi::GtkExpression> for $rust_type {
            #[inline]
            unsafe fn from_glib_full(ptr: *mut crate::ffi::GtkExpression) -> Self {
                from_glib_full(ptr as *mut $ffi_type)
            }
        }

        unsafe impl crate::expression::IsExpression for $rust_type {}

        impl glib::value::ValueType for $rust_type {
            type Type = Self;
        }

        unsafe impl<'a> glib::value::FromValue<'a> for $rust_type {
            type Checker = glib::value::GenericValueTypeOrNoneChecker<Self>;

            #[inline]
            unsafe fn from_value(value: &'a glib::Value) -> Self {
                skip_assert_initialized!();
                from_glib_full(crate::ffi::gtk_value_dup_expression(value.to_glib_none().0))
            }
        }

        impl glib::value::ToValue for $rust_type {
            #[inline]
            fn to_value(&self) -> glib::Value {
                let mut value = glib::Value::for_value_type::<Self>();
                unsafe {
                    crate::ffi::gtk_value_set_expression(
                        value.to_glib_none_mut().0,
                        self.as_ptr() as *mut _,
                    )
                }
                value
            }

            #[inline]
            fn value_type(&self) -> glib::Type {
                use glib::prelude::StaticType;
                Self::static_type()
            }
        }

        impl glib::value::ToValueOptional for $rust_type {
            #[inline]
            fn to_value_optional(s: Option<&Self>) -> glib::Value {
                skip_assert_initialized!();
                let mut value = glib::Value::for_value_type::<Self>();
                unsafe {
                    crate::ffi::gtk_value_set_expression(
                        value.to_glib_none_mut().0,
                        s.map(|s| s.as_ptr()).unwrap_or(std::ptr::null_mut()) as *mut _,
                    )
                }
                value
            }
        }

        impl From<$rust_type> for glib::Value {
            fn from(e: $rust_type) -> Self {
                skip_assert_initialized!();
                let mut value = glib::Value::for_value_type::<$rust_type>();
                unsafe {
                    crate::ffi::gtk_value_take_expression(
                        value.to_glib_none_mut().0,
                        e.into_glib_ptr(),
                    )
                }
                value
            }
        }

        impl glib::HasParamSpec for $rust_type {
            type ParamSpec = crate::ParamSpecExpression;

            type SetValue = $rust_type;

            type BuilderFn = for<'a> fn(&'a str) -> crate::builders::ParamSpecExpressionBuilder<'a>;

            fn param_spec_builder() -> Self::BuilderFn {
                Self::ParamSpec::builder
            }
        }
    };
}