Skip to main content

gstreamer_editing_services/
asset.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{boxed::Box as Box_, pin::Pin};
4
5use glib::{prelude::*, translate::*};
6
7use crate::{Asset, ffi};
8
9impl Asset {
10    // rustdoc-stripper-ignore-next
11    /// Request an asset for a specific extractable type using generics.
12    ///
13    /// # Example
14    /// ```ignore
15    /// let asset = ges::Asset::request::<ges::TestClip>(None)?;
16    /// ```
17    #[doc(alias = "ges_asset_request")]
18    pub fn request<T>(id: Option<&str>) -> Result<Asset, glib::Error>
19    where
20        T: StaticType + IsA<crate::Extractable>,
21    {
22        assert_initialized_main_thread!();
23        unsafe {
24            let mut error = std::ptr::null_mut();
25            let ret = ffi::ges_asset_request(
26                T::static_type().into_glib(),
27                id.to_glib_none().0,
28                &mut error,
29            );
30            if error.is_null() {
31                Ok(from_glib_full(ret))
32            } else {
33                Err(from_glib_full(error))
34            }
35        }
36    }
37
38    // rustdoc-stripper-ignore-next
39    /// Request an asset asynchronously for a specific extractable type using generics.
40    ///
41    /// # Example
42    /// ```ignore
43    /// ges::Asset::request_async::<ges::UriClip, _>(
44    ///     Some("file:///path/to/file.mp4"),
45    ///     None,
46    ///     |result| {
47    ///         match result {
48    ///             Ok(asset) => println!("Asset loaded: {:?}", asset),
49    ///             Err(err) => eprintln!("Failed to load asset: {}", err),
50    ///         }
51    ///     },
52    /// );
53    /// ```
54    #[doc(alias = "ges_asset_request_async")]
55    pub fn request_async<T, P>(
56        id: Option<&str>,
57        cancellable: Option<&impl IsA<gio::Cancellable>>,
58        callback: P,
59    ) where
60        T: StaticType + IsA<crate::Extractable>,
61        P: FnOnce(Result<Asset, glib::Error>) + 'static,
62    {
63        assert_initialized_main_thread!();
64
65        let main_context = glib::MainContext::ref_thread_default();
66        let is_main_context_owner = main_context.is_owner();
67        let has_acquired_main_context = (!is_main_context_owner)
68            .then(|| main_context.acquire().ok())
69            .flatten();
70        assert!(
71            is_main_context_owner || has_acquired_main_context.is_some(),
72            "Async operations only allowed if the thread is owning the MainContext"
73        );
74
75        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
76            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
77        unsafe extern "C" fn request_async_trampoline<
78            P: FnOnce(Result<Asset, glib::Error>) + 'static,
79        >(
80            _source_object: *mut glib::gobject_ffi::GObject,
81            res: *mut gio::ffi::GAsyncResult,
82            user_data: glib::ffi::gpointer,
83        ) {
84            unsafe {
85                let mut error = std::ptr::null_mut();
86                let ret = ffi::ges_asset_request_finish(res, &mut error);
87                let result = if error.is_null() {
88                    Ok(from_glib_full(ret))
89                } else {
90                    Err(from_glib_full(error))
91                };
92                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
93                    Box_::from_raw(user_data as *mut _);
94                let callback: P = callback.into_inner();
95                callback(result);
96            }
97        }
98        let callback = request_async_trampoline::<P>;
99        unsafe {
100            ffi::ges_asset_request_async(
101                T::static_type().into_glib(),
102                id.to_glib_none().0,
103                cancellable.map(|p| p.as_ref()).to_glib_none().0,
104                Some(callback),
105                Box_::into_raw(user_data) as *mut _,
106            );
107        }
108    }
109
110    // rustdoc-stripper-ignore-next
111    /// Request an asset as a future for a specific extractable type.
112    ///
113    /// # Example
114    /// ```ignore
115    /// let asset = ges::Asset::request_future::<ges::UriClip>(Some("file:///path/to/file.mp4")).await?;
116    /// ```
117    pub fn request_future<T>(
118        id: Option<&str>,
119    ) -> Pin<Box_<dyn std::future::Future<Output = Result<Asset, glib::Error>> + 'static>>
120    where
121        T: StaticType + IsA<crate::Extractable> + 'static,
122    {
123        skip_assert_initialized!();
124        let id = id.map(ToOwned::to_owned);
125        Box_::pin(gio::GioFuture::new(&(), move |_obj, cancellable, send| {
126            Self::request_async::<T, _>(
127                id.as_ref().map(::std::borrow::Borrow::borrow),
128                Some(cancellable),
129                move |res| {
130                    send.resolve(res);
131                },
132            );
133        }))
134    }
135
136    // rustdoc-stripper-ignore-next
137    /// Check if an asset needs to be reloaded for a specific extractable type.
138    ///
139    /// # Example
140    /// ```ignore
141    /// if ges::Asset::needs_reload::<ges::UriClip>(Some("file:///path/to/file.mp4")) {
142    ///     println!("Asset needs reload");
143    /// }
144    /// ```
145    #[doc(alias = "ges_asset_needs_reload")]
146    pub fn needs_reload<T>(id: Option<&str>) -> bool
147    where
148        T: StaticType + IsA<crate::Extractable>,
149    {
150        assert_initialized_main_thread!();
151        unsafe {
152            from_glib(ffi::ges_asset_needs_reload(
153                T::static_type().into_glib(),
154                id.to_glib_none().0,
155            ))
156        }
157    }
158}