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
// 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::AsyncResult;
use crate::Cancellable;
use crate::File;
use crate::FileInfo;
use glib::object::IsA;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::pin::Pin;
use std::ptr;

glib::wrapper! {
    /// [`FileEnumerator`][crate::FileEnumerator] allows you to operate on a set of `GFiles`,
    /// returning a [`FileInfo`][crate::FileInfo] structure for each file enumerated (e.g.
    /// [`FileExt::enumerate_children()`][crate::prelude::FileExt::enumerate_children()] will return a [`FileEnumerator`][crate::FileEnumerator] for each
    /// of the children within a directory).
    ///
    /// To get the next file's information from a [`FileEnumerator`][crate::FileEnumerator], 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 `GFileInfos`, 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 `g_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 [`FileEnumerator`][crate::FileEnumerator], use [`FileEnumeratorExt::close()`][crate::prelude::FileEnumeratorExt::close()], or
    /// its asynchronous version, [`FileEnumeratorExt::close_async()`][crate::prelude::FileEnumeratorExt::close_async()]. Once
    /// a [`FileEnumerator`][crate::FileEnumerator] is closed, no further actions may be performed
    /// on it, and it should be freed with `g_object_unref()`.
    ///
    /// # Implements
    ///
    /// [`FileEnumeratorExt`][trait@crate::prelude::FileEnumeratorExt], [`trait@glib::ObjectExt`]
    #[doc(alias = "GFileEnumerator")]
    pub struct FileEnumerator(Object<ffi::GFileEnumerator, ffi::GFileEnumeratorClass>);

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

pub const NONE_FILE_ENUMERATOR: Option<&FileEnumerator> = None;

/// Trait containing all [`struct@FileEnumerator`] methods.
///
/// # Implementors
///
/// [`FileEnumerator`][struct@crate::FileEnumerator]
pub trait FileEnumeratorExt: '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 [`Cancellable`][crate::Cancellable] object, [`None`] to ignore.
    ///
    /// # Returns
    ///
    /// [`true`] on success or [`false`] on error.
    #[doc(alias = "g_file_enumerator_close")]
    fn close<P: IsA<Cancellable>>(&self, cancellable: Option<&P>) -> Result<(), glib::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][io-priority] of the request
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] 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: IsA<Cancellable>, Q: FnOnce(Result<(), glib::Error>) + Send + 'static>(
        &self,
        io_priority: glib::Priority,
        cancellable: Option<&P>,
        callback: Q,
    );

    fn close_async_future(
        &self,
        io_priority: glib::Priority,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>>;

    /// Return a new [`File`][crate::File] 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 [`next_file()`][Self::next_file()].
    ///
    /// 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 [`FileInfo`][crate::FileInfo] gotten from [`next_file()`][Self::next_file()]
    ///  or the async equivalents.
    ///
    /// # Returns
    ///
    /// a [`File`][crate::File] for the [`FileInfo`][crate::FileInfo] passed it.
    #[doc(alias = "g_file_enumerator_get_child")]
    #[doc(alias = "get_child")]
    fn child(&self, info: &FileInfo) -> File;

    /// Get the [`File`][crate::File] container which is being enumerated.
    ///
    /// # Returns
    ///
    /// the [`File`][crate::File] which is being enumerated.
    #[doc(alias = "g_file_enumerator_get_container")]
    #[doc(alias = "get_container")]
    fn container(&self) -> File;

    /// 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;

    /// 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;

    /// Returns information for the next file in the enumerated object.
    /// Will block until the information is available. The [`FileInfo`][crate::FileInfo]
    /// returned from this function will contain attributes that match the
    /// attribute string that was passed when the [`FileEnumerator`][crate::FileEnumerator] was created.
    ///
    /// See the documentation of [`FileEnumerator`][crate::FileEnumerator] 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 [`Cancellable`][crate::Cancellable] object, [`None`] to ignore.
    ///
    /// # Returns
    ///
    /// A [`FileInfo`][crate::FileInfo] 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<P: IsA<Cancellable>>(
        &self,
        cancellable: Option<&P>,
    ) -> Result<Option<FileInfo>, glib::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 [`FileEnumerator`][crate::FileEnumerator] for information about the
    /// order of returned files.
    ///
    /// The callback can be called with less than `num_files` files in case of error
    /// or at the end of the enumerator. In case of a partial error the callback will
    /// be called with any succeeding items and no error, and on the next request the
    /// error will be reported. If a request is cancelled the callback will be called
    /// with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled].
    ///
    /// 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][io-priority] of the request
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] 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: IsA<Cancellable>,
        Q: FnOnce(Result<Vec<FileInfo>, glib::Error>) + Send + 'static,
    >(
        &self,
        num_files: i32,
        io_priority: glib::Priority,
        cancellable: Option<&P>,
        callback: Q,
    );

    fn next_files_async_future(
        &self,
        num_files: i32,
        io_priority: glib::Priority,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<Vec<FileInfo>, glib::Error>> + 'static>>;

    /// 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);
}

impl<O: IsA<FileEnumerator>> FileEnumeratorExt for O {
    fn close<P: IsA<Cancellable>>(&self, cancellable: Option<&P>) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let _ = ffi::g_file_enumerator_close(
                self.as_ref().to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn close_async<P: IsA<Cancellable>, Q: FnOnce(Result<(), glib::Error>) + Send + 'static>(
        &self,
        io_priority: glib::Priority,
        cancellable: Option<&P>,
        callback: Q,
    ) {
        let user_data: Box_<Q> = Box_::new(callback);
        unsafe extern "C" fn close_async_trampoline<
            Q: FnOnce(Result<(), glib::Error>) + Send + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = 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_<Q> = Box_::from_raw(user_data as *mut _);
            callback(result);
        }
        let callback = close_async_trampoline::<Q>;
        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_async_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);
                });
            },
        ))
    }

    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,
            ))
        }
    }

    fn container(&self) -> File {
        unsafe {
            from_glib_none(ffi::g_file_enumerator_get_container(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn has_pending(&self) -> bool {
        unsafe {
            from_glib(ffi::g_file_enumerator_has_pending(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn is_closed(&self) -> bool {
        unsafe {
            from_glib(ffi::g_file_enumerator_is_closed(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn next_file<P: IsA<Cancellable>>(
        &self,
        cancellable: Option<&P>,
    ) -> Result<Option<FileInfo>, glib::Error> {
        unsafe {
            let mut error = 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))
            }
        }
    }

    fn next_files_async<
        P: IsA<Cancellable>,
        Q: FnOnce(Result<Vec<FileInfo>, glib::Error>) + Send + 'static,
    >(
        &self,
        num_files: i32,
        io_priority: glib::Priority,
        cancellable: Option<&P>,
        callback: Q,
    ) {
        let user_data: Box_<Q> = Box_::new(callback);
        unsafe extern "C" fn next_files_async_trampoline<
            Q: FnOnce(Result<Vec<FileInfo>, glib::Error>) + Send + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = 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_<Q> = Box_::from_raw(user_data as *mut _);
            callback(result);
        }
        let callback = next_files_async_trampoline::<Q>;
        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_async_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);
                });
            },
        ))
    }

    fn set_pending(&self, pending: bool) {
        unsafe {
            ffi::g_file_enumerator_set_pending(self.as_ref().to_glib_none().0, pending.into_glib());
        }
    }
}

impl fmt::Display for FileEnumerator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("FileEnumerator")
    }
}