glib/gobject/
binding_group.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
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{fmt, ptr};

use crate::{
    ffi, gobject_ffi, object::ObjectRef, prelude::*, translate::*, Binding, BindingFlags,
    BindingGroup, BoolError, Object, ParamSpec, Value,
};

impl BindingGroup {
    /// Creates a binding between `source_property` on the source object
    /// and `target_property` on `target`. Whenever the `source_property`
    /// is changed the `target_property` is updated using the same value.
    /// The binding flag [`BindingFlags::SYNC_CREATE`][crate::BindingFlags::SYNC_CREATE] is automatically specified.
    ///
    /// See [`ObjectExt::bind_property()`][crate::prelude::ObjectExt::bind_property()] for more information.
    /// ## `source_property`
    /// the property on the source to bind
    /// ## `target`
    /// the target [`Object`][crate::Object]
    /// ## `target_property`
    /// the property on `target` to bind
    /// ## `flags`
    /// the flags used to create the [`Binding`][crate::Binding]
    #[doc(alias = "bind_with_closures")]
    pub fn bind<'a, O: ObjectType>(
        &'a self,
        source_property: &'a str,
        target: &'a O,
        target_property: &'a str,
    ) -> BindingGroupBuilder<'a> {
        BindingGroupBuilder::new(self, source_property, target, target_property)
    }
}

type TransformFn = Option<Box<dyn Fn(&Binding, &Value) -> Option<Value> + Send + Sync + 'static>>;

// rustdoc-stripper-ignore-next
/// Builder for binding group bindings.
#[must_use = "The builder must be built to be used"]
pub struct BindingGroupBuilder<'a> {
    group: &'a BindingGroup,
    source_property: &'a str,
    target: &'a ObjectRef,
    target_property: &'a str,
    flags: BindingFlags,
    transform_to: TransformFn,
    transform_from: TransformFn,
}

impl<'a> fmt::Debug for BindingGroupBuilder<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BindingGroupBuilder")
            .field("group", &self.group)
            .field("source_property", &self.source_property)
            .field("target", &self.target)
            .field("target_property", &self.target_property)
            .field("flags", &self.flags)
            .finish()
    }
}

impl<'a> BindingGroupBuilder<'a> {
    fn new(
        group: &'a BindingGroup,
        source_property: &'a str,
        target: &'a impl ObjectType,
        target_property: &'a str,
    ) -> Self {
        Self {
            group,
            source_property,
            target: target.as_object_ref(),
            target_property,
            flags: BindingFlags::DEFAULT,
            transform_to: None,
            transform_from: None,
        }
    }

    // rustdoc-stripper-ignore-next
    /// Transform changed property values from the target object to the source object with the given closure.
    pub fn transform_from<F: Fn(&Binding, &Value) -> Option<Value> + Send + Sync + 'static>(
        self,
        func: F,
    ) -> Self {
        Self {
            transform_from: Some(Box::new(func)),
            ..self
        }
    }

    // rustdoc-stripper-ignore-next
    /// Transform changed property values from the source object to the target object with the given closure.
    pub fn transform_to<F: Fn(&Binding, &Value) -> Option<Value> + Send + Sync + 'static>(
        self,
        func: F,
    ) -> Self {
        Self {
            transform_to: Some(Box::new(func)),
            ..self
        }
    }

    // rustdoc-stripper-ignore-next
    /// Bind the properties with the given flags.
    pub fn flags(self, flags: BindingFlags) -> Self {
        Self { flags, ..self }
    }

    // rustdoc-stripper-ignore-next
    /// Set the binding flags to [`BIDIRECTIONAL`][crate::BindingFlags::BIDIRECTIONAL].
    pub fn bidirectional(mut self) -> Self {
        self.flags |= crate::BindingFlags::BIDIRECTIONAL;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Set the binding flags to [`SYNC_CREATE`][crate::BindingFlags::SYNC_CREATE].
    pub fn sync_create(mut self) -> Self {
        self.flags |= crate::BindingFlags::SYNC_CREATE;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Set the binding flags to [`INVERT_BOOLEAN`][crate::BindingFlags::INVERT_BOOLEAN].
    pub fn invert_boolean(mut self) -> Self {
        self.flags |= crate::BindingFlags::INVERT_BOOLEAN;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Establish the property binding.
    ///
    /// This fails if the provided properties do not exist.
    pub fn try_build(self) -> Result<(), BoolError> {
        unsafe extern "C" fn transform_to_trampoline(
            binding: *mut gobject_ffi::GBinding,
            from_value: *const gobject_ffi::GValue,
            to_value: *mut gobject_ffi::GValue,
            user_data: ffi::gpointer,
        ) -> ffi::gboolean {
            let transform_data =
                &*(user_data as *const (TransformFn, TransformFn, String, ParamSpec));

            match (transform_data.0.as_ref().unwrap())(
                &from_glib_borrow(binding),
                &*(from_value as *const Value),
            ) {
                None => false,
                Some(res) => {
                    assert!(
                        res.type_().is_a(transform_data.3.value_type()),
                        "Target property {} expected type {} but transform_to function returned {}",
                        transform_data.3.name(),
                        transform_data.3.value_type(),
                        res.type_()
                    );
                    *to_value = res.into_raw();
                    true
                }
            }
            .into_glib()
        }

        unsafe extern "C" fn transform_from_trampoline(
            binding: *mut gobject_ffi::GBinding,
            from_value: *const gobject_ffi::GValue,
            to_value: *mut gobject_ffi::GValue,
            user_data: ffi::gpointer,
        ) -> ffi::gboolean {
            let transform_data =
                &*(user_data as *const (TransformFn, TransformFn, String, ParamSpec));
            let binding = from_glib_borrow(binding);

            match (transform_data.1.as_ref().unwrap())(
                &binding,
                &*(from_value as *const Value),
            ) {
                None => false,
                Some(res) => {
                    let pspec_name = transform_data.2.clone();
                    let source = binding.source().unwrap();
                    let pspec = source.find_property(&pspec_name);
                    assert!(pspec.is_some(), "Source object does not have a property {pspec_name}");
                    let pspec = pspec.unwrap();

                    assert!(
                        res.type_().is_a(pspec.value_type()),
                        "Source property {pspec_name} expected type {} but transform_from function returned {}",
                        pspec.value_type(),
                        res.type_()
                    );
                    *to_value = res.into_raw();
                    true
                }
            }
            .into_glib()
        }

        unsafe extern "C" fn free_transform_data(data: ffi::gpointer) {
            let _ = Box::from_raw(data as *mut (TransformFn, TransformFn, String, ParamSpec));
        }

        let mut _source_property_name_cstr = None;
        let source_property_name = if let Some(source) = self.group.source() {
            let source_property = source.find_property(self.source_property).ok_or_else(|| {
                bool_error!(
                    "Source property {} on type {} not found",
                    self.source_property,
                    source.type_()
                )
            })?;

            // This is NUL-terminated from the C side
            source_property.name().as_ptr()
        } else {
            // This is a Rust &str and needs to be NUL-terminated first
            let source_property_name = std::ffi::CString::new(self.source_property).unwrap();
            let source_property_name_ptr = source_property_name.as_ptr() as *const u8;
            _source_property_name_cstr = Some(source_property_name);

            source_property_name_ptr
        };

        unsafe {
            let target: Object = from_glib_none(self.target.clone().to_glib_none().0);

            let target_property = target.find_property(self.target_property).ok_or_else(|| {
                bool_error!(
                    "Target property {} on type {} not found",
                    self.target_property,
                    target.type_()
                )
            })?;

            let target_property_name = target_property.name().as_ptr();

            let have_transform_to = self.transform_to.is_some();
            let have_transform_from = self.transform_from.is_some();
            let transform_data = if have_transform_to || have_transform_from {
                Box::into_raw(Box::new((
                    self.transform_to,
                    self.transform_from,
                    String::from_glib_none(source_property_name as *const _),
                    target_property,
                )))
            } else {
                ptr::null_mut()
            };

            gobject_ffi::g_binding_group_bind_full(
                self.group.to_glib_none().0,
                source_property_name as *const _,
                target.to_glib_none().0,
                target_property_name as *const _,
                self.flags.into_glib(),
                if have_transform_to {
                    Some(transform_to_trampoline)
                } else {
                    None
                },
                if have_transform_from {
                    Some(transform_from_trampoline)
                } else {
                    None
                },
                transform_data as ffi::gpointer,
                if transform_data.is_null() {
                    None
                } else {
                    Some(free_transform_data)
                },
            );
        }

        Ok(())
    }

    // rustdoc-stripper-ignore-next
    /// Similar to `try_build` but panics instead of failing.
    pub fn build(self) {
        self.try_build().unwrap()
    }
}

#[cfg(test)]
mod test {
    use crate::{prelude::*, subclass::prelude::*};

    #[test]
    fn binding_without_source() {
        let binding_group = crate::BindingGroup::new();

        let source = TestObject::default();
        let target = TestObject::default();

        assert!(source.find_property("name").is_some());
        binding_group
            .bind("name", &target, "name")
            .bidirectional()
            .build();

        binding_group.set_source(Some(&source));

        source.set_name("test_source_name");
        assert_eq!(source.name(), target.name());

        target.set_name("test_target_name");
        assert_eq!(source.name(), target.name());
    }

    #[test]
    fn binding_with_source() {
        let binding_group = crate::BindingGroup::new();

        let source = TestObject::default();
        let target = TestObject::default();

        binding_group.set_source(Some(&source));

        binding_group.bind("name", &target, "name").build();

        source.set_name("test_source_name");
        assert_eq!(source.name(), target.name());
    }

    #[test]
    fn binding_to_transform() {
        let binding_group = crate::BindingGroup::new();

        let source = TestObject::default();
        let target = TestObject::default();

        binding_group.set_source(Some(&source));
        binding_group
            .bind("name", &target, "name")
            .sync_create()
            .transform_to(|_binding, value| {
                let value = value.get::<&str>().unwrap();
                Some(format!("{value} World").to_value())
            })
            .transform_from(|_binding, value| {
                let value = value.get::<&str>().unwrap();
                Some(format!("{value} World").to_value())
            })
            .build();

        source.set_name("Hello");
        assert_eq!(target.name(), "Hello World");
    }

    #[test]
    fn binding_from_transform() {
        let binding_group = crate::BindingGroup::new();

        let source = TestObject::default();
        let target = TestObject::default();

        binding_group.set_source(Some(&source));
        binding_group
            .bind("name", &target, "name")
            .sync_create()
            .bidirectional()
            .transform_to(|_binding, value| {
                let value = value.get::<&str>().unwrap();
                Some(format!("{value} World").to_value())
            })
            .transform_from(|_binding, value| {
                let value = value.get::<&str>().unwrap();
                Some(format!("{value} World").to_value())
            })
            .build();

        target.set_name("Hello");
        assert_eq!(source.name(), "Hello World");
    }

    #[test]
    fn binding_to_transform_change_type() {
        let binding_group = crate::BindingGroup::new();

        let source = TestObject::default();
        let target = TestObject::default();

        binding_group.set_source(Some(&source));
        binding_group
            .bind("name", &target, "enabled")
            .sync_create()
            .transform_to(|_binding, value| {
                let value = value.get::<&str>().unwrap();
                Some((value == "Hello").to_value())
            })
            .transform_from(|_binding, value| {
                let value = value.get::<bool>().unwrap();
                Some((if value { "Hello" } else { "World" }).to_value())
            })
            .build();

        source.set_name("Hello");
        assert!(target.enabled());

        source.set_name("Hello World");
        assert!(!target.enabled());
    }

    #[test]
    fn binding_from_transform_change_type() {
        let binding_group = crate::BindingGroup::new();

        let source = TestObject::default();
        let target = TestObject::default();

        binding_group.set_source(Some(&source));
        binding_group
            .bind("name", &target, "enabled")
            .sync_create()
            .bidirectional()
            .transform_to(|_binding, value| {
                let value = value.get::<&str>().unwrap();
                Some((value == "Hello").to_value())
            })
            .transform_from(|_binding, value| {
                let value = value.get::<bool>().unwrap();
                Some((if value { "Hello" } else { "World" }).to_value())
            })
            .build();

        target.set_enabled(true);
        assert_eq!(source.name(), "Hello");
        target.set_enabled(false);
        assert_eq!(source.name(), "World");
    }

    mod imp {
        use std::{cell::RefCell, sync::OnceLock};

        use super::*;
        use crate as glib;

        #[derive(Debug, Default)]
        pub struct TestObject {
            pub name: RefCell<String>,
            pub enabled: RefCell<bool>,
        }

        #[crate::object_subclass]
        impl ObjectSubclass for TestObject {
            const NAME: &'static str = "TestBindingGroup";
            type Type = super::TestObject;
        }

        impl ObjectImpl for TestObject {
            fn properties() -> &'static [crate::ParamSpec] {
                static PROPERTIES: OnceLock<Vec<crate::ParamSpec>> = OnceLock::new();
                PROPERTIES.get_or_init(|| {
                    vec![
                        crate::ParamSpecString::builder("name")
                            .explicit_notify()
                            .build(),
                        crate::ParamSpecBoolean::builder("enabled")
                            .explicit_notify()
                            .build(),
                    ]
                })
            }

            fn property(&self, _id: usize, pspec: &crate::ParamSpec) -> crate::Value {
                let obj = self.obj();
                match pspec.name() {
                    "name" => obj.name().to_value(),
                    "enabled" => obj.enabled().to_value(),
                    _ => unimplemented!(),
                }
            }

            fn set_property(&self, _id: usize, value: &crate::Value, pspec: &crate::ParamSpec) {
                let obj = self.obj();
                match pspec.name() {
                    "name" => obj.set_name(value.get().unwrap()),
                    "enabled" => obj.set_enabled(value.get().unwrap()),
                    _ => unimplemented!(),
                };
            }
        }
    }

    crate::wrapper! {
        pub struct TestObject(ObjectSubclass<imp::TestObject>);
    }

    impl Default for TestObject {
        fn default() -> Self {
            crate::Object::new()
        }
    }

    impl TestObject {
        fn name(&self) -> String {
            self.imp().name.borrow().clone()
        }

        fn set_name(&self, name: &str) {
            if name != self.imp().name.replace(name.to_string()).as_str() {
                self.notify("name");
            }
        }

        fn enabled(&self) -> bool {
            *self.imp().enabled.borrow()
        }

        fn set_enabled(&self, enabled: bool) {
            if enabled != self.imp().enabled.replace(enabled) {
                self.notify("enabled");
            }
        }
    }
}