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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::ExpressionWatch;
use glib::translate::*;
use glib::{IsA, Object, StaticType, Type, Value};
use std::boxed::Box as Box_;

glib::wrapper! {
    /// [`Expression`][crate::Expression] provides a way to describe references to values.
    ///
    /// An important aspect of expressions is that the value can be obtained
    /// from a source that is several steps away. For example, an expression
    /// may describe ‘the value of property A of `object1`, which is itself the
    /// value of a property of `object2`’. And `object1` may not even exist yet
    /// at the time that the expression is created. This is contrast to `GObject`
    /// property bindings, which can only create direct connections between
    /// the properties of two objects that must both exist for the duration
    /// of the binding.
    ///
    /// An expression needs to be "evaluated" to obtain the value that it currently
    /// refers to. An evaluation always happens in the context of a current object
    /// called `this` (it mirrors the behavior of object-oriented languages),
    /// which may or may not influence the result of the evaluation. Use
    /// [``evaluate()``][`Self::evaluate()`] for evaluating an expression.
    ///
    /// Various methods for defining expressions exist, from simple constants via
    /// [``ConstantExpression::new()``][crate::`ConstantExpression::new()`] to looking up properties in a `GObject`
    /// (even recursively) via [``PropertyExpression::new()``][crate::`PropertyExpression::new()`] or providing
    /// custom functions to transform and combine expressions via
    /// [``ClosureExpression::new()``][crate::`ClosureExpression::new()`].
    ///
    /// Here is an example of a complex expression:
    ///
    /// **⚠️ The following code is in c ⚠️**
    ///
    /// ```c
    ///   color_expr = gtk_property_expression_new (GTK_TYPE_LIST_ITEM,
    ///                                             NULL, "item");
    ///   expression = gtk_property_expression_new (GTK_TYPE_COLOR,
    ///                                             color_expr, "name");
    /// ```
    ///
    /// when evaluated with `this` being a [`ListItem`][crate::ListItem], it will obtain the
    /// "item" property from the [`ListItem`][crate::ListItem], and then obtain the "name" property
    /// from the resulting object (which is assumed to be of type `GTK_TYPE_COLOR`).
    ///
    /// A more concise way to describe this would be
    ///
    /// ```text
    ///   this->item->name
    /// ```
    ///
    /// The most likely place where you will encounter expressions is in the context
    /// of list models and list widgets using them. For example, [`DropDown`][crate::DropDown] is
    /// evaluating a [`Expression`][crate::Expression] to obtain strings from the items in its model
    /// that it can then use to match against the contents of its search entry.
    /// [`StringFilter`][crate::StringFilter] is using a [`Expression`][crate::Expression] for similar reasons.
    ///
    /// By default, expressions are not paying attention to changes and evaluation is
    /// just a snapshot of the current state at a given time. To get informed about
    /// changes, an expression needs to be "watched" via a [`ExpressionWatch`][crate::ExpressionWatch],
    /// which will cause a callback to be called whenever the value of the expression may
    /// have changed; [``watch()``][`Self::watch()`] starts watching an expression, and
    /// [``ExpressionWatch::unwatch()``][crate::`ExpressionWatch::unwatch()`] stops.
    ///
    /// Watches can be created for automatically updating the property of an object,
    /// similar to GObject's `GBinding` mechanism, by using [``bind()``][`Self::bind()`].
    ///
    /// ## GtkExpression in GObject properties
    ///
    /// In order to use a [`Expression`][crate::Expression] as a `GObject` property, you must use the
    /// `gtk_param_spec_expression` when creating a `GParamSpec` to install in the
    /// `GObject` class being defined; for instance:
    ///
    /// **⚠️ The following code is in c ⚠️**
    ///
    /// ```c
    /// obj_props[PROP_EXPRESSION] =
    ///   gtk_param_spec_expression ("expression",
    ///                              "Expression",
    ///                              "The expression used by the widget",
    ///                              G_PARAM_READWRITE |
    ///                              G_PARAM_STATIC_STRINGS |
    ///                              G_PARAM_EXPLICIT_NOTIFY);
    /// ```
    ///
    /// When implementing the `GObjectClass.set_property` and `GObjectClass.get_property`
    /// virtual functions, you must use `gtk_value_get_expression`, to retrieve the
    /// stored [`Expression`][crate::Expression] from the `GValue` container, and `gtk_value_set_expression`,
    /// to store the [`Expression`][crate::Expression] into the `GValue`; for instance:
    ///
    /// **⚠️ The following code is in c ⚠️**
    ///
    /// ```c
    ///   // in set_property()...
    ///   case PROP_EXPRESSION:
    ///     foo_widget_set_expression (foo, gtk_value_get_expression (value));
    ///     break;
    ///
    ///   // in get_property()...
    ///   case PROP_EXPRESSION:
    ///     gtk_value_set_expression (value, foo->expression);
    ///     break;
    /// ```
    ///
    /// ## GtkExpression in .ui files
    ///
    /// [`Builder`][crate::Builder] has support for creating expressions. The syntax here can be used where
    /// a [`Expression`][crate::Expression] object is needed like in a ``<property>`` tag for an expression
    /// property, or in a ``<binding>`` tag to bind a property to an expression.
    ///
    /// To create an property expression, use the ``<lookup>`` element. It can have a `type`
    /// attribute to specify the object type, and a `name` attribute to specify the property
    /// to look up. The content of ``<lookup>`` can either be an element specfiying the expression
    /// to use the object, or a string that specifies the name of the object to use.
    ///
    /// Example:
    ///
    /// ```xml
    ///   <lookup name='search'>string_filter</lookup>
    /// ```
    ///
    /// To create a constant expression, use the ``<constant>`` element. If the type attribute
    /// is specified, the element content is interpreted as a value of that type. Otherwise,
    /// it is assumed to be an object. For instance:
    ///
    /// ```xml
    ///   <constant>string_filter</constant>
    ///   <constant type='gchararray'>Hello, world</constant>
    /// ```
    ///
    /// To create a closure expression, use the ``<closure>`` element. The `type` and `function`
    /// attributes specify what function to use for the closure, the content of the element
    /// contains the expressions for the parameters. For instance:
    ///
    /// ```xml
    ///   <closure type='gchararray' function='combine_args_somehow'>
    ///     <constant type='gchararray'>File size:</constant>
    ///     <lookup type='GFile' name='size'>myfile</lookup>
    ///   </closure>
    /// ```
    ///
    /// This is an Abstract Base Class, you cannot instantiate it.
    #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    #[doc(alias = "GtkExpression")]
    pub struct Expression(Shared<ffi::GtkExpression>);

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

impl glib::StaticType for Expression {
    #[doc(alias = "gtk_expression_get_type")]
    fn static_type() -> Type {
        unsafe { from_glib(ffi::gtk_expression_get_type()) }
    }
}

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

pub const NONE_EXPRESSION: Option<&Expression> = None;

pub unsafe trait IsExpression:
    glib::StaticType + FromGlibPtrFull<*mut ffi::GtkExpression> + 'static
{
}

impl Expression {
    pub fn downcast<E: IsExpression>(self) -> Result<E, Expression> {
        unsafe {
            if self.type_() == E::static_type() {
                Ok(from_glib_full(self.to_glib_full()))
            } else {
                Err(self)
            }
        }
    }

    pub fn downcast_ref<E: IsExpression>(&self) -> Option<&E> {
        unsafe {
            if self.type_() == E::static_type() {
                Some(&*(self as *const Expression as *const E))
            } else {
                None
            }
        }
    }
    #[doc(alias = "get_type")]
    pub fn type_(&self) -> Type {
        unsafe {
            let ptr = self.to_glib_none().0;

            from_glib((*(*(ptr as *mut glib::gobject_ffi::GTypeInstance)).g_class).g_type)
        }
    }

    /// Gets the `GType` that this expression evaluates to.
    ///
    /// This type is constant and will not change over the lifetime
    /// of this expression.
    ///
    /// # Returns
    ///
    /// The type returned from [``evaluate()``][`Self::evaluate()`]
    #[doc(alias = "gtk_expression_get_value_type")]
    #[doc(alias = "get_value_type")]
    pub fn value_type(&self) -> Type {
        assert_initialized_main_thread!();
        unsafe { from_glib(ffi::gtk_expression_get_value_type(self.to_glib_none().0)) }
    }

    /// Checks if the expression is static.
    ///
    /// A static expression will never change its result when
    /// [``evaluate()``][`Self::evaluate()`] is called on it with the same arguments.
    ///
    /// That means a call to [``watch()``][`Self::watch()`] is not necessary because
    /// it will never trigger a notify.
    ///
    /// # Returns
    ///
    /// `TRUE` if the expression is static
    #[doc(alias = "gtk_expression_is_static")]
    pub fn is_static(&self) -> bool {
        assert_initialized_main_thread!();
        unsafe { from_glib(ffi::gtk_expression_is_static(self.to_glib_none().0)) }
    }

    /// Bind `target`'s property named `property` to `self`.
    ///
    /// The value that `self` evaluates to is set via ``g_object_set()`` on
    /// `target`. This is repeated whenever `self` changes to ensure that
    /// the object's property stays synchronized with `self`.
    ///
    /// If `self`'s evaluation fails, `target`'s `property` is not updated.
    /// You can ensure that this doesn't happen by using a fallback
    /// expression.
    ///
    /// Note that this function takes ownership of `self`. If you want
    /// to keep it around, you should `Gtk::`Expression::ref()`` it beforehand.
    /// ## `target`
    /// the target object to bind to
    /// ## `property`
    /// name of the property on `target` to bind to
    /// ## `this_`
    /// the this argument for
    ///  the evaluation of `self`
    ///
    /// # Returns
    ///
    /// a [`ExpressionWatch`][crate::ExpressionWatch]
    #[doc(alias = "gtk_expression_bind")]
    pub fn bind<T: IsA<Object>, U: IsA<Object>>(
        &self,
        target: &T,
        property_name: &str,
        this: Option<&U>,
    ) -> ExpressionWatch {
        assert_initialized_main_thread!();
        unsafe {
            from_glib_none(ffi::gtk_expression_bind(
                self.to_glib_full(),
                target.as_ref().to_glib_none().0,
                property_name.to_glib_none().0,
                this.map(|t| t.as_ref()).to_glib_none().0,
            ))
        }
    }

    /// Evaluates the given expression and on success stores the result
    /// in `value`.
    ///
    /// The `GType` of `value` will be the type given by
    /// [``value_type()``][`Self::value_type()`].
    ///
    /// It is possible that expressions cannot be evaluated - for example
    /// when the expression references objects that have been destroyed or
    /// set to `NULL`. In that case `value` will remain empty and `FALSE`
    /// will be returned.
    /// ## `this_`
    /// the this argument for the evaluation
    /// ## `value`
    /// an empty `GValue`
    ///
    /// # Returns
    ///
    /// `TRUE` if the expression could be evaluated
    #[doc(alias = "gtk_expression_evaluate")]
    pub fn evaluate<T: IsA<Object>>(&self, this: Option<&T>) -> 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
            }
        }
    }

    /// Watch the given `expression` for changes.
    ///
    /// The `notify` function will be called whenever the evaluation of `self`
    /// may have changed.
    ///
    /// GTK cannot guarantee that the evaluation did indeed change when the `notify`
    /// gets invoked, but it guarantees the opposite: When it did in fact change,
    /// the `notify` will be invoked.
    /// ## `this_`
    /// the `this` argument to
    ///  watch
    /// ## `notify`
    /// callback to invoke when the expression changes
    ///
    /// # Returns
    ///
    /// The newly installed watch. Note that the only
    ///  reference held to the watch will be released when the watch is unwatched
    ///  which can happen automatically, and not just via
    ///  [``ExpressionWatch::unwatch()``][crate::`ExpressionWatch::unwatch()`]. You should call `Gtk::`ExpressionWatch::ref()``
    ///  if you want to keep the watch around.
    #[doc(alias = "gtk_expression_watch")]
    pub fn watch<T: IsA<Object>, F: Fn() + 'static>(
        &self,
        this: Option<&T>,
        notify: F,
    ) -> ExpressionWatch {
        assert_initialized_main_thread!();
        unsafe extern "C" fn notify_trampoline<F: Fn() + 'static>(user_data: glib::ffi::gpointer) {
            let f: &F = &*(user_data as *const F);
            f()
        }
        unsafe extern "C" fn destroy_func<F: Fn() + 'static>(user_data: glib::ffi::gpointer) {
            let _callback: Box_<Option<Box_<F>>> = Box_::from_raw(user_data as *mut _);
        }
        let callback_data: Box_<F> = Box_::new(notify);
        unsafe {
            from_glib_none(ffi::gtk_expression_watch(
                self.to_glib_none().0,
                this.map(|t| t.as_ref()).to_glib_none().0,
                Some(notify_trampoline::<F> as _),
                Box_::into_raw(callback_data) as *mut _,
                Some(destroy_func::<F> as _),
            ))
        }
    }
}

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

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

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

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

    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 { ffi::gtk_value_set_expression(value.to_glib_none_mut().0, s.to_glib_none().0) }
        value
    }
}

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

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

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

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

            pub fn upcast_ref(&self) -> &crate::Expression {
                &*self
            }
        }

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

        impl glib::StaticType for $rust_type {
            fn static_type() -> glib::Type {
                unsafe { glib::translate::FromGlib::from_glib($get_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>;

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

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

            fn value_type(&self) -> glib::Type {
                use glib::StaticType;
                Self::static_type()
            }
        }

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