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

use std::marker::PhantomData;

use glib::{object::IsClass, prelude::*, Type};

use crate::{value::GstValueExt, IdStr};

impl crate::Object {
    // rustdoc-stripper-ignore-next
    /// Builds a `GObjectBuilder` targeting type `O`.
    #[inline]
    pub fn builder<'a, O>() -> GObjectBuilder<'a, O>
    where
        O: IsA<crate::Object> + IsClass,
    {
        assert_initialized_main_thread!();
        GObjectBuilder {
            type_: Some(O::static_type()),
            properties: smallvec::SmallVec::new(),
            phantom: PhantomData,
        }
    }

    // rustdoc-stripper-ignore-next
    /// Builds a `GObjectBuilder` targeting base class of type `O` and concrete `type_`.
    #[inline]
    pub fn builder_for<'a, O>(type_: Type) -> GObjectBuilder<'a, O>
    where
        O: IsA<crate::Object> + IsClass,
    {
        assert_initialized_main_thread!();
        GObjectBuilder {
            type_: Some(type_),
            properties: smallvec::SmallVec::new(),
            phantom: PhantomData,
        }
    }

    // rustdoc-stripper-ignore-next
    /// Builds a `GObjectBuilder` targeting base class of type `O`
    /// and a concrete `Type` that will be specified later.
    ///
    /// This is useful when the concrete type of the object is dynamically determined
    /// when calling the `build()` method of a wrapping builder.
    #[inline]
    pub fn builder_for_deferred_type<'a, O>() -> GObjectBuilder<'a, O>
    where
        O: IsA<crate::Object> + IsClass,
    {
        assert_initialized_main_thread!();
        GObjectBuilder {
            type_: None,
            properties: smallvec::SmallVec::new(),
            phantom: PhantomData,
        }
    }
}

#[derive(Debug, Eq, PartialEq, thiserror::Error)]
pub enum GObjectError {
    #[error("property {property} for type {type_} not found")]
    PropertyNotFound { type_: Type, property: IdStr },

    #[error("property {property} for type {type_} can't be set from string {value}")]
    PropertyFromStr {
        type_: Type,
        property: IdStr,
        value: IdStr,
    },
}

fn value_from_property_str(
    pspec: glib::ParamSpec,
    value: &str,
) -> Result<glib::Value, GObjectError> {
    skip_assert_initialized!(); // Already checked transitively by caller

    if pspec.value_type() == crate::Structure::static_type() && value == "NULL" {
        Ok(None::<crate::Structure>.to_value())
    } else {
        cfg_if::cfg_if! {
            if #[cfg(feature = "v1_20")] {
                let res = glib::Value::deserialize_with_pspec(value, &pspec);
            } else {
                let res = glib::Value::deserialize(value, pspec.value_type());
            }
        }
        res.map_err(|_| GObjectError::PropertyFromStr {
            type_: pspec.owner_type(),
            property: pspec.name().into(),
            value: value.into(),
        })
    }
}

pub trait GObjectExtManualGst: IsA<glib::Object> + 'static {
    #[doc(alias = "gst_util_set_object_arg")]
    #[track_caller]
    fn set_property_from_str(&self, name: &str, value: &str) {
        let pspec = self.find_property(name).unwrap_or_else(|| {
            panic!("property '{}' of type '{}' not found", name, self.type_());
        });

        self.set_property(name, value_from_property_str(pspec, value).unwrap())
    }
}

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

// rustdoc-stripper-ignore-next
/// Builder for `GObject`s.
#[must_use = "The builder must be built to be used"]
pub struct GObjectBuilder<'a, O> {
    type_: Option<Type>,
    properties: smallvec::SmallVec<[(&'a str, ValueOrStr<'a>); 16]>,
    phantom: PhantomData<O>,
}

enum ValueOrStr<'a> {
    Value(glib::Value),
    Str(&'a str),
}

impl<'a, O: IsA<crate::Object> + IsClass> GObjectBuilder<'a, O> {
    // rustdoc-stripper-ignore-next
    /// Sets the concrete `Type`.
    ///
    /// This should be used on an `GObjectBuilder` created with
    /// [`GObjectBuilder::for_deferred_type`].
    #[inline]
    pub fn type_(mut self, type_: Type) -> Self {
        self.type_ = Some(type_);
        self
    }

    // rustdoc-stripper-ignore-next
    /// Sets property `name` to the given value `value`.
    ///
    /// Overrides any default or previously defined value for `name`.
    #[inline]
    pub fn property(self, name: &'a str, value: impl Into<glib::Value> + 'a) -> Self {
        Self {
            properties: {
                let mut properties = self.properties;
                properties.push((name, ValueOrStr::Value(value.into())));
                properties
            },
            ..self
        }
    }

    // rustdoc-stripper-ignore-next
    /// Sets property `name` to the given string value `value`.
    #[inline]
    pub fn property_from_str(self, name: &'a str, value: &'a str) -> Self {
        Self {
            properties: {
                let mut properties = self.properties;
                properties.push((name, ValueOrStr::Str(value)));
                properties
            },
            ..self
        }
    }

    impl_builder_gvalue_extra_setters!(property_and_name);

    // rustdoc-stripper-ignore-next
    /// Builds the [`Object`] with the provided properties.
    ///
    /// This fails if there is no such element factory or the element factory can't be loaded.
    ///
    /// # Panics
    ///
    /// This panics if:
    ///
    /// * The [`Object`] is not instantiable, doesn't have all the given properties or
    ///   property values of the wrong type are provided.
    /// * The [`GObjectBuilder`] was created for a deferred concrete `Type` but
    ///   the `Type` was not set.
    ///
    /// [`Object`]: crate::Object
    #[track_caller]
    #[must_use = "Building the element without using it has no effect"]
    pub fn build(self) -> Result<O, GObjectError> {
        let type_ = self.type_.expect("Deferred Type must be set");

        let mut properties = smallvec::SmallVec::<[_; 16]>::with_capacity(self.properties.len());
        let klass = glib::Class::<O>::from_type(type_).unwrap();
        for (name, value) in self.properties {
            let pspec =
                klass
                    .find_property(name)
                    .ok_or_else(|| GObjectError::PropertyNotFound {
                        type_,
                        property: name.into(),
                    })?;

            match value {
                ValueOrStr::Value(value) => properties.push((name, value)),
                ValueOrStr::Str(value) => {
                    properties.push((name, value_from_property_str(pspec, value)?));
                }
            }
        }

        let object =
            unsafe { glib::Object::with_mut_values(type_, &mut properties).unsafe_cast::<O>() };

        Ok(object)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{prelude::*, Bin, Element, ElementFactory, Object};

    #[test]
    fn test_set_property_from_str() {
        crate::init().unwrap();

        let fakesink = ElementFactory::make("fakesink").build().unwrap();
        fakesink.set_property_from_str("state-error", "ready-to-paused");
        let v = fakesink.property_value("state-error");
        let (_klass, e) = glib::EnumValue::from_value(&v).unwrap();
        assert_eq!(e.nick(), "ready-to-paused");
    }

    #[test]
    fn builder() {
        crate::init().unwrap();

        let msg_fwd = "message-forward";
        let bin = Object::builder::<Bin>()
            .name("test-bin")
            .property("async-handling", true)
            .property_from_str(msg_fwd, "True")
            .build()
            .unwrap();

        assert_eq!(bin.name(), "test-bin");
        assert!(bin.property::<bool>("async-handling"));
        assert!(bin.property::<bool>("message-forward"));
    }

    #[test]
    fn builder_err() {
        crate::init().unwrap();

        assert_eq!(
            Object::builder::<Bin>()
                .property("not-a-prop", true)
                .build(),
            Err(GObjectError::PropertyNotFound {
                type_: Bin::static_type(),
                property: idstr!("not-a-prop")
            })
        );

        assert_eq!(
            Object::builder::<Bin>()
                .property_from_str("async-handling", "not-a-bool")
                .build(),
            Err(GObjectError::PropertyFromStr {
                type_: Bin::static_type(),
                property: idstr!("async-handling"),
                value: idstr!("not-a-bool")
            })
        );
    }

    #[test]
    fn builder_for() {
        crate::init().unwrap();

        let fakesink = ElementFactory::make("fakesink").build().unwrap();

        let fakesink = Object::builder_for::<Element>(fakesink.type_())
            .name("test-fakesink")
            .property("can-activate-pull", true)
            .property_from_str("state-error", "ready-to-paused")
            .build()
            .unwrap();

        assert_eq!(fakesink.name(), "test-fakesink");
        assert!(fakesink.property::<bool>("can-activate-pull"));
        let v = fakesink.property_value("state-error");
        let (_klass, e) = glib::EnumValue::from_value(&v).unwrap();
        assert_eq!(e.nick(), "ready-to-paused");
    }
}