gio/auto/
file_enumerator.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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::{ffi, AsyncResult, Cancellable, File, FileInfo};
use glib::{prelude::*, translate::*};
use std::{boxed::Box as Box_, pin::Pin};

glib::wrapper! {
    /// `GFileEnumerator` allows you to operate on a set of [`File`][crate::File] objects,
    /// returning a [`FileInfo`][crate::FileInfo] structure for each file enumerated (e.g.
    /// [`FileExt::enumerate_children()`][crate::prelude::FileExt::enumerate_children()] will return a `GFileEnumerator` for each
    /// of the children within a directory).
    ///
    /// To get the next file's information from a `GFileEnumerator`, use
    /// [`FileEnumeratorExt::next_file()`][crate::prelude::FileEnumeratorExt::next_file()] or its asynchronous version,
    /// [`FileEnumeratorExt::next_files_async()`][crate::prelude::FileEnumeratorExt::next_files_async()]. Note that the asynchronous
    /// version will return a list of [`FileInfo`][crate::FileInfo] objects, whereas the
    /// synchronous will only return the next file in the enumerator.
    ///
    /// The ordering of returned files is unspecified for non-Unix
    /// platforms; for more information, see `GLib::Dir::read_name()`.  On Unix,
    /// when operating on local files, returned files will be sorted by
    /// inode number.  Effectively you can assume that the ordering of
    /// returned files will be stable between successive calls (and
    /// applications) assuming the directory is unchanged.
    ///
    /// If your application needs a specific ordering, such as by name or
    /// modification time, you will have to implement that in your
    /// application code.
    ///
    /// To close a `GFileEnumerator`, use [`FileEnumeratorExt::close()`][crate::prelude::FileEnumeratorExt::close()], or
    /// its asynchronous version, [`FileEnumeratorExt::close_async()`][crate::prelude::FileEnumeratorExt::close_async()]. Once
    /// a `GFileEnumerator` is closed, no further actions may be performed
    /// on it, and it should be freed with `GObject::Object::unref()`.
    ///
    /// ## Properties
    ///
    ///
    /// #### `container`
    ///  The container that is being enumerated.
    ///
    /// Writeable | Construct Only
    ///
    /// # Implements
    ///
    /// [`FileEnumeratorExt`][trait@crate::prelude::FileEnumeratorExt], [`trait@glib::ObjectExt`], [`FileEnumeratorExtManual`][trait@crate::prelude::FileEnumeratorExtManual]
    #[doc(alias = "GFileEnumerator")]
    pub struct FileEnumerator(Object<ffi::GFileEnumerator, ffi::GFileEnumeratorClass>);

    match fn {
        type_ => || ffi::g_file_enumerator_get_type(),
    }
}

impl FileEnumerator {
    pub const NONE: Option<&'static FileEnumerator> = None;
}

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

/// Trait containing all [`struct@FileEnumerator`] methods.
///
/// # Implementors
///
/// [`FileEnumerator`][struct@crate::FileEnumerator]
pub trait FileEnumeratorExt: IsA<FileEnumerator> + sealed::Sealed + 'static {
    /// Releases all resources used by this enumerator, making the
    /// enumerator return [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed] on all calls.
    ///
    /// This will be automatically called when the last reference
    /// is dropped, but you might want to call this function to make
    /// sure resources are released as early as possible.
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore.
    ///
    /// # Returns
    ///
    /// #TRUE on success or #FALSE on error.
    #[doc(alias = "g_file_enumerator_close")]
    fn close(&self, cancellable: Option<&impl IsA<Cancellable>>) -> Result<(), glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let is_ok = ffi::g_file_enumerator_close(
                self.as_ref().to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronously closes the file enumerator.
    ///
    /// If @cancellable is not [`None`], then the operation can be cancelled by
    /// triggering the cancellable object from another thread. If the operation
    /// was cancelled, the error [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] will be returned in
    /// g_file_enumerator_close_finish().
    /// ## `io_priority`
    /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore.
    /// ## `callback`
    /// a #GAsyncReadyCallback
    ///   to call when the request is satisfied
    #[doc(alias = "g_file_enumerator_close_async")]
    fn close_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
        &self,
        io_priority: glib::Priority,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn close_async_trampoline<
            P: FnOnce(Result<(), glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let _ = ffi::g_file_enumerator_close_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = close_async_trampoline::<P>;
        unsafe {
            ffi::g_file_enumerator_close_async(
                self.as_ref().to_glib_none().0,
                io_priority.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn close_future(
        &self,
        io_priority: glib::Priority,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.close_async(io_priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    /// Return a new #GFile which refers to the file named by @info in the source
    /// directory of @self.  This function is primarily intended to be used
    /// inside loops with g_file_enumerator_next_file().
    ///
    /// To use this, [`FILE_ATTRIBUTE_STANDARD_NAME`][crate::FILE_ATTRIBUTE_STANDARD_NAME] must have been listed in the
    /// attributes list used when creating the #GFileEnumerator.
    ///
    /// This is a convenience method that's equivalent to:
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///   gchar *name = g_file_info_get_name (info);
    ///   GFile *child = g_file_get_child (g_file_enumerator_get_container (enumr),
    ///                                    name);
    /// ```
    /// ## `info`
    /// a #GFileInfo gotten from g_file_enumerator_next_file()
    ///   or the async equivalents.
    ///
    /// # Returns
    ///
    /// a #GFile for the #GFileInfo passed it.
    #[doc(alias = "g_file_enumerator_get_child")]
    #[doc(alias = "get_child")]
    fn child(&self, info: &FileInfo) -> File {
        unsafe {
            from_glib_full(ffi::g_file_enumerator_get_child(
                self.as_ref().to_glib_none().0,
                info.to_glib_none().0,
            ))
        }
    }

    /// Get the #GFile container which is being enumerated.
    ///
    /// # Returns
    ///
    /// the #GFile which is being enumerated.
    #[doc(alias = "g_file_enumerator_get_container")]
    #[doc(alias = "get_container")]
    fn container(&self) -> File {
        unsafe {
            from_glib_none(ffi::g_file_enumerator_get_container(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Checks if the file enumerator has pending operations.
    ///
    /// # Returns
    ///
    /// [`true`] if the @self has pending operations.
    #[doc(alias = "g_file_enumerator_has_pending")]
    fn has_pending(&self) -> bool {
        unsafe {
            from_glib(ffi::g_file_enumerator_has_pending(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Checks if the file enumerator has been closed.
    ///
    /// # Returns
    ///
    /// [`true`] if the @self is closed.
    #[doc(alias = "g_file_enumerator_is_closed")]
    fn is_closed(&self) -> bool {
        unsafe {
            from_glib(ffi::g_file_enumerator_is_closed(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Returns information for the next file in the enumerated object.
    /// Will block until the information is available. The #GFileInfo
    /// returned from this function will contain attributes that match the
    /// attribute string that was passed when the #GFileEnumerator was created.
    ///
    /// See the documentation of #GFileEnumerator for information about the
    /// order of returned files.
    ///
    /// On error, returns [`None`] and sets @error to the error. If the
    /// enumerator is at the end, [`None`] will be returned and @error will
    /// be unset.
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore.
    ///
    /// # Returns
    ///
    /// A #GFileInfo or [`None`] on error
    ///    or end of enumerator.  Free the returned object with
    ///    g_object_unref() when no longer needed.
    #[doc(alias = "g_file_enumerator_next_file")]
    fn next_file(
        &self,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<Option<FileInfo>, glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::g_file_enumerator_next_file(
                self.as_ref().to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Request information for a number of files from the enumerator asynchronously.
    /// When all I/O for the operation is finished the @callback will be called with
    /// the requested information.
    ///
    /// See the documentation of #GFileEnumerator for information about the
    /// order of returned files.
    ///
    /// Once the end of the enumerator is reached, or if an error occurs, the
    /// @callback will be called with an empty list. In this case, the previous call
    /// to g_file_enumerator_next_files_async() will typically have returned fewer
    /// than @num_files items.
    ///
    /// If a request is cancelled the callback will be called with
    /// [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled].
    ///
    /// This leads to the following pseudo-code usage:
    ///
    /// ```text
    /// g_autoptr(GFile) dir = get_directory ();
    /// g_autoptr(GFileEnumerator) enumerator = NULL;
    /// g_autolist(GFileInfo) files = NULL;
    /// g_autoptr(GError) local_error = NULL;
    ///
    /// enumerator = yield g_file_enumerate_children_async (dir,
    ///                                                     G_FILE_ATTRIBUTE_STANDARD_NAME ","
    ///                                                     G_FILE_ATTRIBUTE_STANDARD_TYPE,
    ///                                                     G_FILE_QUERY_INFO_NONE,
    ///                                                     G_PRIORITY_DEFAULT,
    ///                                                     cancellable,
    ///                                                     …,
    ///                                                     &local_error);
    /// if (enumerator == NULL)
    ///   g_error ("Error enumerating: %s", local_error->message);
    ///
    /// // Loop until no files are returned, either because the end of the enumerator
    /// // has been reached, or an error was returned.
    /// do
    ///   {
    ///     files = yield g_file_enumerator_next_files_async (enumerator,
    ///                                                       5,  // number of files to request
    ///                                                       G_PRIORITY_DEFAULT,
    ///                                                       cancellable,
    ///                                                       …,
    ///                                                       &local_error);
    ///
    ///     // Process the returned files, but don’t assume that exactly 5 were returned.
    ///     for (GList *l = files; l != NULL; l = l->next)
    ///       {
    ///         GFileInfo *info = l->data;
    ///         handle_file_info (info);
    ///       }
    ///   }
    /// while (files != NULL);
    ///
    /// if (local_error != NULL &&
    ///     !g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
    ///   g_error ("Error while enumerating: %s", local_error->message);
    /// ```
    ///
    /// During an async request no other sync and async calls are allowed, and will
    /// result in [`IOErrorEnum::Pending`][crate::IOErrorEnum::Pending] errors.
    ///
    /// Any outstanding I/O request with higher priority (lower numerical value) will
    /// be executed before an outstanding request with lower priority. Default
    /// priority is `G_PRIORITY_DEFAULT`.
    /// ## `num_files`
    /// the number of file info objects to request
    /// ## `io_priority`
    /// the [I/O priority](iface.AsyncResult.html#io-priority) of the request
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore.
    /// ## `callback`
    /// a #GAsyncReadyCallback
    ///   to call when the request is satisfied
    #[doc(alias = "g_file_enumerator_next_files_async")]
    fn next_files_async<P: FnOnce(Result<Vec<FileInfo>, glib::Error>) + 'static>(
        &self,
        num_files: i32,
        io_priority: glib::Priority,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn next_files_async_trampoline<
            P: FnOnce(Result<Vec<FileInfo>, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let ret =
                ffi::g_file_enumerator_next_files_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(FromGlibPtrContainer::from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = next_files_async_trampoline::<P>;
        unsafe {
            ffi::g_file_enumerator_next_files_async(
                self.as_ref().to_glib_none().0,
                num_files,
                io_priority.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn next_files_future(
        &self,
        num_files: i32,
        io_priority: glib::Priority,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<Vec<FileInfo>, glib::Error>> + 'static>>
    {
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.next_files_async(num_files, io_priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    /// Sets the file enumerator as having pending operations.
    /// ## `pending`
    /// a boolean value.
    #[doc(alias = "g_file_enumerator_set_pending")]
    fn set_pending(&self, pending: bool) {
        unsafe {
            ffi::g_file_enumerator_set_pending(self.as_ref().to_glib_none().0, pending.into_glib());
        }
    }
}

impl<O: IsA<FileEnumerator>> FileEnumeratorExt for O {}