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

use crate::{ffi, prelude::*, Formatter};
use glib::{subclass::prelude::*, translate::*};

pub trait FormatterImpl: FormatterImplExt + ObjectImpl + Send + Sync {
    /// Whether the URI can be loaded
    fn can_load_uri(&self, uri: &str) -> Result<(), glib::Error> {
        self.parent_can_load_uri(uri)
    }

    /// Load data from the given URI into timeline.
    ///
    /// # Deprecated since 1.18
    ///
    /// Use [`TimelineExt::load_from_uri()`][crate::prelude::TimelineExt::load_from_uri()]
    /// ## `timeline`
    /// a [`Timeline`][crate::Timeline]
    /// ## `uri`
    /// a `gchar` * pointing to a URI
    ///
    /// # Returns
    ///
    /// TRUE if the timeline data was successfully loaded from the URI,
    /// else FALSE.
    fn load_from_uri(&self, timeline: &crate::Timeline, uri: &str) -> Result<(), glib::Error> {
        self.parent_load_from_uri(timeline, uri)
    }

    /// Save data from timeline to the given URI.
    ///
    /// # Deprecated since 1.18
    ///
    /// Use [`TimelineExt::save_to_uri()`][crate::prelude::TimelineExt::save_to_uri()]
    /// ## `timeline`
    /// a [`Timeline`][crate::Timeline]
    /// ## `uri`
    /// a `gchar` * pointing to a URI
    /// ## `overwrite`
    /// [`true`] to overwrite file if it exists
    ///
    /// # Returns
    ///
    /// TRUE if the timeline data was successfully saved to the URI
    /// else FALSE.
    fn save_to_uri(
        &self,
        timeline: &crate::Timeline,
        uri: &str,
        overwrite: bool,
    ) -> Result<(), glib::Error> {
        self.parent_save_to_uri(timeline, uri, overwrite)
    }
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::FormatterImplExt> Sealed for T {}
}

pub trait FormatterImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_can_load_uri(&self, uri: &str) -> Result<(), glib::Error> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GESFormatterClass;

            let f = (*parent_class)
                .can_load_uri
                .expect("Missing parent function `can_load_uri`");

            let mut error = std::ptr::null_mut();
            let res = f(
                self.obj()
                    .unsafe_cast_ref::<crate::Formatter>()
                    .to_glib_none()
                    .0,
                uri.to_glib_none().0,
                &mut error,
            );

            if res == glib::ffi::GFALSE {
                if error.is_null() {
                    Err(glib::Error::new(
                        gst::CoreError::Failed,
                        "Can load uri failed",
                    ))
                } else {
                    Err(from_glib_full(error))
                }
            } else {
                Ok(())
            }
        }
    }

    fn parent_load_from_uri(
        &self,
        timeline: &crate::Timeline,
        uri: &str,
    ) -> Result<(), glib::Error> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GESFormatterClass;

            let f = (*parent_class)
                .load_from_uri
                .expect("Missing parent function `load_from_uri`");

            let mut error = std::ptr::null_mut();
            let res = f(
                self.obj()
                    .unsafe_cast_ref::<crate::Formatter>()
                    .to_glib_none()
                    .0,
                timeline
                    .unsafe_cast_ref::<crate::Timeline>()
                    .to_glib_none()
                    .0,
                uri.to_glib_none().0,
                &mut error,
            );

            if res == glib::ffi::GFALSE {
                if error.is_null() {
                    Err(glib::Error::new(
                        gst::CoreError::Failed,
                        "Load from uri failed",
                    ))
                } else {
                    Err(from_glib_full(error))
                }
            } else {
                Ok(())
            }
        }
    }
    fn parent_save_to_uri(
        &self,
        timeline: &crate::Timeline,
        uri: &str,
        overwrite: bool,
    ) -> Result<(), glib::Error> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GESFormatterClass;

            let f = (*parent_class)
                .save_to_uri
                .expect("Missing parent function `save_to_uri`");

            let mut error = std::ptr::null_mut();
            let res = f(
                self.obj()
                    .unsafe_cast_ref::<crate::Formatter>()
                    .to_glib_none()
                    .0,
                timeline
                    .unsafe_cast_ref::<crate::Timeline>()
                    .to_glib_none()
                    .0,
                uri.to_glib_none().0,
                overwrite.into_glib(),
                &mut error,
            );

            if res == glib::ffi::GFALSE {
                if error.is_null() {
                    Err(glib::Error::new(
                        gst::CoreError::Failed,
                        "Save to uri failed",
                    ))
                } else {
                    Err(from_glib_full(error))
                }
            } else {
                Ok(())
            }
        }
    }
}

impl<T: FormatterImpl> FormatterImplExt for T {}

unsafe impl<T: FormatterImpl> IsSubclassable<T> for Formatter {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.can_load_uri = Some(formatter_can_load_uri::<T>);
        klass.load_from_uri = Some(formatter_load_from_uri::<T>);
        klass.save_to_uri = Some(formatter_save_to_uri::<T>);
    }
}

unsafe extern "C" fn formatter_can_load_uri<T: FormatterImpl>(
    ptr: *mut ffi::GESFormatter,
    uri: *const libc::c_char,
    error: *mut *mut glib::ffi::GError,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    match imp.can_load_uri(glib::GString::from_glib_borrow(uri).as_str()) {
        Err(err) => {
            if !error.is_null() {
                *error = err.into_glib_ptr();
            }

            glib::ffi::GFALSE
        }
        Ok(_) => glib::ffi::GTRUE,
    }
}

unsafe extern "C" fn formatter_load_from_uri<T: FormatterImpl>(
    ptr: *mut ffi::GESFormatter,
    timeline: *mut ffi::GESTimeline,
    uri: *const libc::c_char,
    error: *mut *mut glib::ffi::GError,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let timeline = from_glib_borrow(timeline);

    match imp.load_from_uri(&timeline, glib::GString::from_glib_borrow(uri).as_str()) {
        Err(err) => {
            if !error.is_null() {
                *error = err.into_glib_ptr();
            }

            glib::ffi::GFALSE
        }
        Ok(_) => glib::ffi::GTRUE,
    }
}

unsafe extern "C" fn formatter_save_to_uri<T: FormatterImpl>(
    ptr: *mut ffi::GESFormatter,
    timeline: *mut ffi::GESTimeline,
    uri: *const libc::c_char,
    overwrite: glib::ffi::gboolean,
    error: *mut *mut glib::ffi::GError,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let timeline = from_glib_borrow(timeline);

    match imp.save_to_uri(
        &timeline,
        glib::GString::from_glib_borrow(uri).as_str(),
        from_glib(overwrite),
    ) {
        Err(err) => {
            if !error.is_null() {
                *error = err.into_glib_ptr();
            }

            glib::ffi::GFALSE
        }
        Ok(_) => glib::ffi::GTRUE,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Formatter;

    pub mod imp {
        use super::*;

        #[derive(Default)]
        pub struct SimpleFormatter;

        #[glib::object_subclass]
        impl ObjectSubclass for SimpleFormatter {
            const NAME: &'static str = "SimpleFormatter";
            type Type = super::SimpleFormatter;
            type ParentType = Formatter;
        }
        impl ObjectImpl for SimpleFormatter {}
        impl FormatterImpl for SimpleFormatter {
            fn can_load_uri(&self, uri: &str) -> Result<(), glib::Error> {
                if uri.starts_with("ges:test") {
                    Ok(())
                } else {
                    self.parent_can_load_uri(uri)
                }
            }

            fn load_from_uri(
                &self,
                timeline: &crate::Timeline,
                _uri: &str,
            ) -> Result<(), glib::Error> {
                timeline.append_layer();

                Ok(())
            }

            fn save_to_uri(
                &self,
                timeline: &crate::Timeline,
                uri: &str,
                _overwrite: bool,
            ) -> Result<(), glib::Error> {
                unsafe { timeline.set_data("saved", uri.to_string()) };

                Ok(())
            }
        }
    }

    glib::wrapper! {
        pub struct SimpleFormatter(ObjectSubclass<imp::SimpleFormatter>) @extends Formatter, gst::Object;
    }

    impl SimpleFormatter {
        pub fn new() -> Self {
            glib::Object::builder().build()
        }
    }

    impl Default for SimpleFormatter {
        fn default() -> Self {
            Self::new()
        }
    }

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

        let formatter = SimpleFormatter::new();
        formatter
            .can_load_uri("ges:test:")
            .expect("We can load anything...");

        assert!(formatter.can_load_uri("nottest").is_err());

        let timeline = crate::Timeline::new();
        assert_eq!(timeline.layers().len(), 0);
        #[allow(deprecated)]
        formatter
            .load_from_uri(&timeline, "test")
            .expect("We can load anything...");
        assert_eq!(timeline.layers().len(), 1);

        unsafe {
            assert_eq!(timeline.data::<Option<String>>("saved"), None);
        }
        #[allow(deprecated)]
        formatter
            .save_to_uri(&timeline, "test", false)
            .expect("We can save anything...");
        unsafe {
            assert_eq!(
                timeline.data::<String>("saved").unwrap().as_ref(),
                &"test".to_string()
            );
        }

        Formatter::register(
            SimpleFormatter::static_type(),
            "SimpleFormatter",
            None,
            None,
            None,
            1.0,
            gst::Rank::PRIMARY,
        );

        let proj = crate::Project::new(Some("ges:test:"));
        let timeline = proj
            .extract()
            .unwrap()
            .downcast::<crate::Timeline>()
            .unwrap();
        assert_eq!(timeline.layers().len(), 1);

        let proj = crate::Project::new(Some("ges:notest:"));
        assert!(proj.extract().is_err());
    }
}