gio/auto/
file_enumerator.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::{AsyncResult, Cancellable, File, FileInfo, ffi};
6use glib::{prelude::*, translate::*};
7use std::{boxed::Box as Box_, pin::Pin};
8
9glib::wrapper! {
10    /// `GFileEnumerator` allows you to operate on a set of [`File`][crate::File] objects,
11    /// returning a [`FileInfo`][crate::FileInfo] structure for each file enumerated (e.g.
12    /// [`FileExt::enumerate_children()`][crate::prelude::FileExt::enumerate_children()] will return a `GFileEnumerator` for each
13    /// of the children within a directory).
14    ///
15    /// To get the next file's information from a `GFileEnumerator`, use
16    /// [`FileEnumeratorExt::next_file()`][crate::prelude::FileEnumeratorExt::next_file()] or its asynchronous version,
17    /// [`FileEnumeratorExt::next_files_async()`][crate::prelude::FileEnumeratorExt::next_files_async()]. Note that the asynchronous
18    /// version will return a list of [`FileInfo`][crate::FileInfo] objects, whereas the
19    /// synchronous will only return the next file in the enumerator.
20    ///
21    /// The ordering of returned files is unspecified for non-Unix
22    /// platforms; for more information, see `GLib::Dir::read_name()`.  On Unix,
23    /// when operating on local files, returned files will be sorted by
24    /// inode number.  Effectively you can assume that the ordering of
25    /// returned files will be stable between successive calls (and
26    /// applications) assuming the directory is unchanged.
27    ///
28    /// If your application needs a specific ordering, such as by name or
29    /// modification time, you will have to implement that in your
30    /// application code.
31    ///
32    /// To close a `GFileEnumerator`, use [`FileEnumeratorExtManual::close()`][crate::prelude::FileEnumeratorExtManual::close()], or
33    /// its asynchronous version, [`FileEnumeratorExt::close_async()`][crate::prelude::FileEnumeratorExt::close_async()]. Once
34    /// a `GFileEnumerator` is closed, no further actions may be performed
35    /// on it, and it should be freed with `GObject::Object::unref()`.
36    ///
37    /// ## Properties
38    ///
39    ///
40    /// #### `container`
41    ///  The container that is being enumerated.
42    ///
43    /// Writeable | Construct Only
44    ///
45    /// # Implements
46    ///
47    /// [`FileEnumeratorExt`][trait@crate::prelude::FileEnumeratorExt], [`trait@glib::ObjectExt`], [`FileEnumeratorExtManual`][trait@crate::prelude::FileEnumeratorExtManual]
48    #[doc(alias = "GFileEnumerator")]
49    pub struct FileEnumerator(Object<ffi::GFileEnumerator, ffi::GFileEnumeratorClass>);
50
51    match fn {
52        type_ => || ffi::g_file_enumerator_get_type(),
53    }
54}
55
56impl FileEnumerator {
57    pub const NONE: Option<&'static FileEnumerator> = None;
58}
59
60/// Trait containing all [`struct@FileEnumerator`] methods.
61///
62/// # Implementors
63///
64/// [`FileEnumerator`][struct@crate::FileEnumerator]
65pub trait FileEnumeratorExt: IsA<FileEnumerator> + 'static {
66    /// Asynchronously closes the file enumerator.
67    ///
68    /// If @cancellable is not [`None`], then the operation can be cancelled by
69    /// triggering the cancellable object from another thread. If the operation
70    /// was cancelled, the error [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] will be returned in
71    /// g_file_enumerator_close_finish().
72    /// ## `io_priority`
73    /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
74    /// ## `cancellable`
75    /// optional #GCancellable object, [`None`] to ignore.
76    /// ## `callback`
77    /// a #GAsyncReadyCallback
78    ///   to call when the request is satisfied
79    #[doc(alias = "g_file_enumerator_close_async")]
80    fn close_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
81        &self,
82        io_priority: glib::Priority,
83        cancellable: Option<&impl IsA<Cancellable>>,
84        callback: P,
85    ) {
86        let main_context = glib::MainContext::ref_thread_default();
87        let is_main_context_owner = main_context.is_owner();
88        let has_acquired_main_context = (!is_main_context_owner)
89            .then(|| main_context.acquire().ok())
90            .flatten();
91        assert!(
92            is_main_context_owner || has_acquired_main_context.is_some(),
93            "Async operations only allowed if the thread is owning the MainContext"
94        );
95
96        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
97            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
98        unsafe extern "C" fn close_async_trampoline<
99            P: FnOnce(Result<(), glib::Error>) + 'static,
100        >(
101            _source_object: *mut glib::gobject_ffi::GObject,
102            res: *mut crate::ffi::GAsyncResult,
103            user_data: glib::ffi::gpointer,
104        ) {
105            unsafe {
106                let mut error = std::ptr::null_mut();
107                ffi::g_file_enumerator_close_finish(_source_object as *mut _, res, &mut error);
108                let result = if error.is_null() {
109                    Ok(())
110                } else {
111                    Err(from_glib_full(error))
112                };
113                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
114                    Box_::from_raw(user_data as *mut _);
115                let callback: P = callback.into_inner();
116                callback(result);
117            }
118        }
119        let callback = close_async_trampoline::<P>;
120        unsafe {
121            ffi::g_file_enumerator_close_async(
122                self.as_ref().to_glib_none().0,
123                io_priority.into_glib(),
124                cancellable.map(|p| p.as_ref()).to_glib_none().0,
125                Some(callback),
126                Box_::into_raw(user_data) as *mut _,
127            );
128        }
129    }
130
131    fn close_future(
132        &self,
133        io_priority: glib::Priority,
134    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
135        Box_::pin(crate::GioFuture::new(
136            self,
137            move |obj, cancellable, send| {
138                obj.close_async(io_priority, Some(cancellable), move |res| {
139                    send.resolve(res);
140                });
141            },
142        ))
143    }
144
145    /// Return a new #GFile which refers to the file named by @info in the source
146    /// directory of @self.  This function is primarily intended to be used
147    /// inside loops with g_file_enumerator_next_file().
148    ///
149    /// To use this, [`FILE_ATTRIBUTE_STANDARD_NAME`][crate::FILE_ATTRIBUTE_STANDARD_NAME] must have been listed in the
150    /// attributes list used when creating the #GFileEnumerator.
151    ///
152    /// This is a convenience method that's equivalent to:
153    ///
154    ///
155    /// **⚠️ The following code is in C ⚠️**
156    ///
157    /// ```C
158    ///   gchar *name = g_file_info_get_name (info);
159    ///   GFile *child = g_file_get_child (g_file_enumerator_get_container (enumr),
160    ///                                    name);
161    /// ```
162    /// ## `info`
163    /// a #GFileInfo gotten from g_file_enumerator_next_file()
164    ///   or the async equivalents.
165    ///
166    /// # Returns
167    ///
168    /// a #GFile for the #GFileInfo passed it.
169    #[doc(alias = "g_file_enumerator_get_child")]
170    #[doc(alias = "get_child")]
171    fn child(&self, info: &FileInfo) -> File {
172        unsafe {
173            from_glib_full(ffi::g_file_enumerator_get_child(
174                self.as_ref().to_glib_none().0,
175                info.to_glib_none().0,
176            ))
177        }
178    }
179
180    /// Get the #GFile container which is being enumerated.
181    ///
182    /// # Returns
183    ///
184    /// the #GFile which is being enumerated.
185    #[doc(alias = "g_file_enumerator_get_container")]
186    #[doc(alias = "get_container")]
187    fn container(&self) -> File {
188        unsafe {
189            from_glib_none(ffi::g_file_enumerator_get_container(
190                self.as_ref().to_glib_none().0,
191            ))
192        }
193    }
194
195    /// Checks if the file enumerator has pending operations.
196    ///
197    /// # Returns
198    ///
199    /// [`true`] if the @self has pending operations.
200    #[doc(alias = "g_file_enumerator_has_pending")]
201    fn has_pending(&self) -> bool {
202        unsafe {
203            from_glib(ffi::g_file_enumerator_has_pending(
204                self.as_ref().to_glib_none().0,
205            ))
206        }
207    }
208
209    /// Checks if the file enumerator has been closed.
210    ///
211    /// # Returns
212    ///
213    /// [`true`] if the @self is closed.
214    #[doc(alias = "g_file_enumerator_is_closed")]
215    fn is_closed(&self) -> bool {
216        unsafe {
217            from_glib(ffi::g_file_enumerator_is_closed(
218                self.as_ref().to_glib_none().0,
219            ))
220        }
221    }
222
223    /// Returns information for the next file in the enumerated object.
224    /// Will block until the information is available. The #GFileInfo
225    /// returned from this function will contain attributes that match the
226    /// attribute string that was passed when the #GFileEnumerator was created.
227    ///
228    /// See the documentation of #GFileEnumerator for information about the
229    /// order of returned files.
230    ///
231    /// On error, returns [`None`] and sets @error to the error. If the
232    /// enumerator is at the end, [`None`] will be returned and @error will
233    /// be unset.
234    /// ## `cancellable`
235    /// optional #GCancellable object, [`None`] to ignore.
236    ///
237    /// # Returns
238    ///
239    /// A #GFileInfo or [`None`] on error
240    ///    or end of enumerator.  Free the returned object with
241    ///    g_object_unref() when no longer needed.
242    #[doc(alias = "g_file_enumerator_next_file")]
243    fn next_file(
244        &self,
245        cancellable: Option<&impl IsA<Cancellable>>,
246    ) -> Result<Option<FileInfo>, glib::Error> {
247        unsafe {
248            let mut error = std::ptr::null_mut();
249            let ret = ffi::g_file_enumerator_next_file(
250                self.as_ref().to_glib_none().0,
251                cancellable.map(|p| p.as_ref()).to_glib_none().0,
252                &mut error,
253            );
254            if error.is_null() {
255                Ok(from_glib_full(ret))
256            } else {
257                Err(from_glib_full(error))
258            }
259        }
260    }
261
262    /// Request information for a number of files from the enumerator asynchronously.
263    /// When all I/O for the operation is finished the @callback will be called with
264    /// the requested information.
265    ///
266    /// See the documentation of #GFileEnumerator for information about the
267    /// order of returned files.
268    ///
269    /// Once the end of the enumerator is reached, or if an error occurs, the
270    /// @callback will be called with an empty list. In this case, the previous call
271    /// to g_file_enumerator_next_files_async() will typically have returned fewer
272    /// than @num_files items.
273    ///
274    /// If a request is cancelled the callback will be called with
275    /// [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled].
276    ///
277    /// This leads to the following pseudo-code usage:
278    ///
279    /// ```text
280    /// g_autoptr(GFile) dir = get_directory ();
281    /// g_autoptr(GFileEnumerator) enumerator = NULL;
282    /// g_autolist(GFileInfo) files = NULL;
283    /// g_autoptr(GError) local_error = NULL;
284    ///
285    /// enumerator = yield g_file_enumerate_children_async (dir,
286    ///                                                     G_FILE_ATTRIBUTE_STANDARD_NAME ","
287    ///                                                     G_FILE_ATTRIBUTE_STANDARD_TYPE,
288    ///                                                     G_FILE_QUERY_INFO_NONE,
289    ///                                                     G_PRIORITY_DEFAULT,
290    ///                                                     cancellable,
291    ///                                                     …,
292    ///                                                     &local_error);
293    /// if (enumerator == NULL)
294    ///   g_error ("Error enumerating: %s", local_error->message);
295    ///
296    /// // Loop until no files are returned, either because the end of the enumerator
297    /// // has been reached, or an error was returned.
298    /// do
299    ///   {
300    ///     files = yield g_file_enumerator_next_files_async (enumerator,
301    ///                                                       5,  // number of files to request
302    ///                                                       G_PRIORITY_DEFAULT,
303    ///                                                       cancellable,
304    ///                                                       …,
305    ///                                                       &local_error);
306    ///
307    ///     // Process the returned files, but don’t assume that exactly 5 were returned.
308    ///     for (GList *l = files; l != NULL; l = l->next)
309    ///       {
310    ///         GFileInfo *info = l->data;
311    ///         handle_file_info (info);
312    ///       }
313    ///   }
314    /// while (files != NULL);
315    ///
316    /// if (local_error != NULL &&
317    ///     !g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
318    ///   g_error ("Error while enumerating: %s", local_error->message);
319    /// ```
320    ///
321    /// During an async request no other sync and async calls are allowed, and will
322    /// result in [`IOErrorEnum::Pending`][crate::IOErrorEnum::Pending] errors.
323    ///
324    /// Any outstanding I/O request with higher priority (lower numerical value) will
325    /// be executed before an outstanding request with lower priority. Default
326    /// priority is `G_PRIORITY_DEFAULT`.
327    /// ## `num_files`
328    /// the number of file info objects to request
329    /// ## `io_priority`
330    /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
331    /// ## `cancellable`
332    /// optional #GCancellable object, [`None`] to ignore.
333    /// ## `callback`
334    /// a #GAsyncReadyCallback
335    ///   to call when the request is satisfied
336    #[doc(alias = "g_file_enumerator_next_files_async")]
337    fn next_files_async<P: FnOnce(Result<Vec<FileInfo>, glib::Error>) + 'static>(
338        &self,
339        num_files: i32,
340        io_priority: glib::Priority,
341        cancellable: Option<&impl IsA<Cancellable>>,
342        callback: P,
343    ) {
344        let main_context = glib::MainContext::ref_thread_default();
345        let is_main_context_owner = main_context.is_owner();
346        let has_acquired_main_context = (!is_main_context_owner)
347            .then(|| main_context.acquire().ok())
348            .flatten();
349        assert!(
350            is_main_context_owner || has_acquired_main_context.is_some(),
351            "Async operations only allowed if the thread is owning the MainContext"
352        );
353
354        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
355            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
356        unsafe extern "C" fn next_files_async_trampoline<
357            P: FnOnce(Result<Vec<FileInfo>, glib::Error>) + 'static,
358        >(
359            _source_object: *mut glib::gobject_ffi::GObject,
360            res: *mut crate::ffi::GAsyncResult,
361            user_data: glib::ffi::gpointer,
362        ) {
363            unsafe {
364                let mut error = std::ptr::null_mut();
365                let ret = ffi::g_file_enumerator_next_files_finish(
366                    _source_object as *mut _,
367                    res,
368                    &mut error,
369                );
370                let result = if error.is_null() {
371                    Ok(FromGlibPtrContainer::from_glib_full(ret))
372                } else {
373                    Err(from_glib_full(error))
374                };
375                let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
376                    Box_::from_raw(user_data as *mut _);
377                let callback: P = callback.into_inner();
378                callback(result);
379            }
380        }
381        let callback = next_files_async_trampoline::<P>;
382        unsafe {
383            ffi::g_file_enumerator_next_files_async(
384                self.as_ref().to_glib_none().0,
385                num_files,
386                io_priority.into_glib(),
387                cancellable.map(|p| p.as_ref()).to_glib_none().0,
388                Some(callback),
389                Box_::into_raw(user_data) as *mut _,
390            );
391        }
392    }
393
394    fn next_files_future(
395        &self,
396        num_files: i32,
397        io_priority: glib::Priority,
398    ) -> Pin<Box_<dyn std::future::Future<Output = Result<Vec<FileInfo>, glib::Error>> + 'static>>
399    {
400        Box_::pin(crate::GioFuture::new(
401            self,
402            move |obj, cancellable, send| {
403                obj.next_files_async(num_files, io_priority, Some(cancellable), move |res| {
404                    send.resolve(res);
405                });
406            },
407        ))
408    }
409
410    /// Sets the file enumerator as having pending operations.
411    /// ## `pending`
412    /// a boolean value.
413    #[doc(alias = "g_file_enumerator_set_pending")]
414    fn set_pending(&self, pending: bool) {
415        unsafe {
416            ffi::g_file_enumerator_set_pending(self.as_ref().to_glib_none().0, pending.into_glib());
417        }
418    }
419}
420
421impl<O: IsA<FileEnumerator>> FileEnumeratorExt for O {}