Skip to main content

gio/auto/
resource.rs

1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir-files (https://github.com/gtk-rs/gir-files)
3// DO NOT EDIT
4
5use crate::{InputStream, ResourceLookupFlags, ffi};
6use glib::translate::*;
7
8glib::wrapper! {
9    /// s more common to use the
10    /// `--generate-source` and `--generate-header` arguments to create a source file
11    /// and header to link directly into your application.
12    /// This will generate `get_resource()`, `register_resource()` and
13    /// `unregister_resource()` functions, prefixed by the `--c-name` argument passed
14    /// to [`glib-compile-resources`](glib-compile-resources.html). `get_resource()`
15    /// returns the generated `GResource` object. The register and unregister
16    /// functions register the resource so its files can be accessed using
17    /// [`resources_lookup_data()`][crate::resources_lookup_data()].
18    ///
19    /// Once a `GResource` has been created and registered all the data in it can be
20    /// accessed globally in the process by using API calls like
21    /// [`resources_open_stream()`][crate::resources_open_stream()] to stream the data or
22    /// [`resources_lookup_data()`][crate::resources_lookup_data()] to get a direct pointer to the data. You can
23    /// also use URIs like `resource:///org/gtk/Example/data/splashscreen.png` with
24    /// [`File`][crate::File] to access the resource data.
25    ///
26    /// Some higher-level APIs, such as [`GtkApplication`](https://docs.gtk.org/gtk4/class.Application.html),
27    /// will automatically load resources from certain well-known paths in the
28    /// resource namespace as a convenience. See the documentation for those APIs
29    /// for details.
30    ///
31    /// There are two forms of the generated source, the default version uses the
32    /// compiler support for constructor and destructor functions (where available)
33    /// to automatically create and register the `GResource` on startup or library
34    /// load time. If you pass `--manual-register`, two functions to
35    /// register/unregister the resource are created instead. This requires an
36    /// explicit initialization call in your application/library, but it works on all
37    /// platforms, even on the minor ones where constructors are not supported.
38    /// (Constructor support is available for at least Win32, Mac OS and Linux.)
39    ///
40    /// Note that resource data can point directly into the data segment of e.g. a
41    /// library, so if you are unloading libraries during runtime you need to be very
42    /// careful with keeping around pointers to data from a resource, as this goes
43    /// away when the library is unloaded. However, in practice this is not generally
44    /// a problem, since most resource accesses are for your own resources, and
45    /// resource data is often used once, during parsing, and then released.
46    ///
47    /// # Overlays
48    ///
49    /// When debugging a program or testing a change to an installed version, it is
50    /// often useful to be able to replace resources in the program or library,
51    /// without recompiling, for debugging or quick hacking and testing purposes.
52    /// Since GLib 2.50, it is possible to use the `G_RESOURCE_OVERLAYS` environment
53    /// variable to selectively overlay resources with replacements from the
54    /// filesystem.  It is a `G_SEARCHPATH_SEPARATOR`-separated list of substitutions
55    /// to perform during resource lookups. It is ignored when running in a setuid
56    /// process.
57    ///
58    /// A substitution has the form
59    ///
60    /// ```text
61    /// /org/gtk/libgtk=/home/desrt/gtk-overlay
62    /// ```
63    ///
64    /// The part before the `=` is the resource subpath for which the overlay
65    /// applies.  The part after is a filesystem path which contains files and
66    /// subdirectories as you would like to be loaded as resources with the
67    /// equivalent names.
68    ///
69    /// In the example above, if an application tried to load a resource with the
70    /// resource path `/org/gtk/libgtk/ui/gtkdialog.ui` then `GResource` would check
71    /// the filesystem path `/home/desrt/gtk-overlay/ui/gtkdialog.ui`.  If a file was
72    /// found there, it would be used instead.  This is an overlay, not an outright
73    /// replacement, which means that if a file is not found at that path, the
74    /// built-in version will be used instead.  Whiteouts are not currently
75    /// supported.
76    ///
77    /// Substitutions must start with a slash, and must not contain a trailing slash
78    /// before the `=`.  The filesystem path after the `=` should ideally be absolute,
79    /// but this is not strictly required.  It is possible to overlay the location of
80    /// a single resource with an individual file.
81    #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
82    pub struct Resource(Shared<ffi::GResource>);
83
84    match fn {
85        ref => |ptr| ffi::g_resource_ref(ptr),
86        unref => |ptr| ffi::g_resource_unref(ptr),
87        type_ => || ffi::g_resource_get_type(),
88    }
89}
90
91impl Resource {
92    /// Returns all the names of children at the specified @path in the resource.
93    ///
94    /// The return result is a `NULL` terminated list of strings which should
95    /// be released with `strfreev()`.
96    ///
97    /// If @path is invalid or does not exist in the [`Resource`][crate::Resource],
98    /// [`ResourceError::NotFound`][crate::ResourceError::NotFound] will be returned.
99    ///
100    /// @lookup_flags controls the behaviour of the lookup.
101    /// ## `path`
102    /// A path name inside the resource
103    /// ## `lookup_flags`
104    /// A [`ResourceLookupFlags`][crate::ResourceLookupFlags]
105    ///
106    /// # Returns
107    ///
108    /// an array of constant strings
109    #[doc(alias = "g_resource_enumerate_children")]
110    pub fn enumerate_children(
111        &self,
112        path: &str,
113        lookup_flags: ResourceLookupFlags,
114    ) -> Result<Vec<glib::GString>, glib::Error> {
115        unsafe {
116            let mut error = std::ptr::null_mut();
117            let ret = ffi::g_resource_enumerate_children(
118                self.to_glib_none().0,
119                path.to_glib_none().0,
120                lookup_flags.into_glib(),
121                &mut error,
122            );
123            if error.is_null() {
124                Ok(FromGlibPtrContainer::from_glib_full(ret))
125            } else {
126                Err(from_glib_full(error))
127            }
128        }
129    }
130
131    /// Looks for a file at the specified @path in the resource and
132    /// if found returns information about it.
133    ///
134    /// @lookup_flags controls the behaviour of the lookup.
135    ///
136    /// The only error this can return is [`ResourceError::NotFound`][crate::ResourceError::NotFound], if @path was
137    /// not found in @self.
138    /// ## `path`
139    /// A path name inside the resource
140    /// ## `lookup_flags`
141    /// A [`ResourceLookupFlags`][crate::ResourceLookupFlags]
142    ///
143    /// # Returns
144    ///
145    /// `TRUE` if the file was found, `FALSE` if there were errors
146    ///
147    /// ## `size`
148    /// a location to place the length of the contents of the file,
149    ///    or `NULL` if the length is not needed
150    ///
151    /// ## `flags`
152    /// a location to place the flags about the file,
153    ///    or `NULL` if the length is not needed
154    #[doc(alias = "g_resource_get_info")]
155    #[doc(alias = "get_info")]
156    pub fn info(
157        &self,
158        path: &str,
159        lookup_flags: ResourceLookupFlags,
160    ) -> Result<(usize, u32), glib::Error> {
161        unsafe {
162            let mut size = std::mem::MaybeUninit::uninit();
163            let mut flags = std::mem::MaybeUninit::uninit();
164            let mut error = std::ptr::null_mut();
165            let is_ok = ffi::g_resource_get_info(
166                self.to_glib_none().0,
167                path.to_glib_none().0,
168                lookup_flags.into_glib(),
169                size.as_mut_ptr(),
170                flags.as_mut_ptr(),
171                &mut error,
172            );
173            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
174            if error.is_null() {
175                Ok((size.assume_init(), flags.assume_init()))
176            } else {
177                Err(from_glib_full(error))
178            }
179        }
180    }
181
182    /// Returns whether the specified @path in the resource
183    /// has children.
184    /// ## `path`
185    /// A pathname inside the resource
186    ///
187    /// # Returns
188    ///
189    /// [`true`] if @path has children
190    #[cfg(feature = "v2_84")]
191    #[cfg_attr(docsrs, doc(cfg(feature = "v2_84")))]
192    #[doc(alias = "g_resource_has_children")]
193    pub fn has_children(&self, path: &str) -> bool {
194        unsafe {
195            from_glib(ffi::g_resource_has_children(
196                self.to_glib_none().0,
197                path.to_glib_none().0,
198            ))
199        }
200    }
201
202    /// Looks for a file at the specified @path in the resource and
203    /// returns a [`glib::Bytes`][crate::glib::Bytes] that lets you directly access the data in
204    /// memory.
205    ///
206    /// The data is always followed by a zero byte, so you
207    /// can safely use the data as a C string. However, that byte
208    /// is not included in the size of the [`glib::Bytes`][crate::glib::Bytes].
209    ///
210    /// For uncompressed resource files this is a pointer directly into
211    /// the resource bundle, which is typically in some read-only data section
212    /// in the program binary. For compressed files, memory is allocated on
213    /// the heap and the data is automatically uncompressed.
214    ///
215    /// @lookup_flags controls the behaviour of the lookup.
216    ///
217    /// This can return error [`ResourceError::NotFound`][crate::ResourceError::NotFound] if @path was not found in
218    /// @self, or [`ResourceError::Internal`][crate::ResourceError::Internal] if decompression of a compressed
219    /// resource failed.
220    /// ## `path`
221    /// A path name inside the resource
222    /// ## `lookup_flags`
223    /// A [`ResourceLookupFlags`][crate::ResourceLookupFlags]
224    ///
225    /// # Returns
226    ///
227    /// [`glib::Bytes`][crate::glib::Bytes] or `NULL` on error
228    #[doc(alias = "g_resource_lookup_data")]
229    pub fn lookup_data(
230        &self,
231        path: &str,
232        lookup_flags: ResourceLookupFlags,
233    ) -> Result<glib::Bytes, glib::Error> {
234        unsafe {
235            let mut error = std::ptr::null_mut();
236            let ret = ffi::g_resource_lookup_data(
237                self.to_glib_none().0,
238                path.to_glib_none().0,
239                lookup_flags.into_glib(),
240                &mut error,
241            );
242            if error.is_null() {
243                Ok(from_glib_full(ret))
244            } else {
245                Err(from_glib_full(error))
246            }
247        }
248    }
249
250    /// Looks for a file at the specified @path in the resource and
251    /// returns a [`InputStream`][crate::InputStream] that lets you read the data.
252    ///
253    /// @lookup_flags controls the behaviour of the lookup.
254    ///
255    /// The only error this can return is [`ResourceError::NotFound`][crate::ResourceError::NotFound], if @path was
256    /// not found in @self.
257    /// ## `path`
258    /// A path name inside the resource
259    /// ## `lookup_flags`
260    /// A [`ResourceLookupFlags`][crate::ResourceLookupFlags]
261    ///
262    /// # Returns
263    ///
264    /// [`InputStream`][crate::InputStream] or `NULL` on error
265    #[doc(alias = "g_resource_open_stream")]
266    pub fn open_stream(
267        &self,
268        path: &str,
269        lookup_flags: ResourceLookupFlags,
270    ) -> Result<InputStream, glib::Error> {
271        unsafe {
272            let mut error = std::ptr::null_mut();
273            let ret = ffi::g_resource_open_stream(
274                self.to_glib_none().0,
275                path.to_glib_none().0,
276                lookup_flags.into_glib(),
277                &mut error,
278            );
279            if error.is_null() {
280                Ok(from_glib_full(ret))
281            } else {
282                Err(from_glib_full(error))
283            }
284        }
285    }
286
287    /// t exist, or
288    /// there is an error in reading it, an error from `GLib::MappedFile::new()`
289    /// will be returned.
290    /// ## `filename`
291    /// the path of a filename to load, in the GLib filename encoding
292    ///
293    /// # Returns
294    ///
295    /// a new [`Resource`][crate::Resource], or `NULL` on error
296    #[doc(alias = "g_resource_load")]
297    pub fn load(filename: impl AsRef<std::path::Path>) -> Result<Resource, glib::Error> {
298        unsafe {
299            let mut error = std::ptr::null_mut();
300            let ret = ffi::g_resource_load(filename.as_ref().to_glib_none().0, &mut error);
301            if error.is_null() {
302                Ok(from_glib_full(ret))
303            } else {
304                Err(from_glib_full(error))
305            }
306        }
307    }
308}