gio 0.22.2

Rust bindings for the Gio library
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
// Take a look at the license at the top of the repository in the LICENSE file.

use glib::{prelude::*, subclass::prelude::*, translate::*};
use std::pin::Pin;

use crate::{
    AsyncResult, Cancellable, FileEnumerator, FileInfo, GioFuture, IOErrorEnum, LocalTask, ffi,
    prelude::*,
};

// Support custom implementation of virtual functions defined in `gio::ffi::GFileEnumeratorClass` except pairs `xxx_async/xxx_finish` for which GIO provides a default implementation (which should be ok).
// TODO: overriding these default implementations might still be useful for subclasses (if they can do something better than blocking IO).
pub trait FileEnumeratorImpl: ObjectImpl + ObjectSubclass<Type: IsA<FileEnumerator>> {
    fn next_file(
        &self,
        cancellable: Option<&Cancellable>,
    ) -> Result<Option<FileInfo>, glib::Error> {
        self.parent_next_file(cancellable)
    }

    fn next_files_future(
        &self,
        num_files: i32,
        priority: glib::Priority,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<glib::List<FileInfo>, glib::Error>> + 'static>,
    > {
        self.parent_next_files_future(num_files, priority)
    }

    // rustdoc-stripper-ignore-next
    /// Closes the enumerator (see [`FileEnumeratorExt::close`]).
    ///
    /// NOTE: If the enumerator has not been explicitly closed, GIO closes it when the object is dropped.
    /// But GIO does it by calling `close` vfunc in `finalize`, which is not safe and could lead to undefined behavior,
    /// such as accessing freed memory or resources, which can cause crashes or other unexpected behavior.
    ///
    /// An issue has been opened in GLib to address this: <https://gitlab.gnome.org/GNOME/glib/-/issues/3713> and a MR has been opened to fix it: <https://gitlab.gnome.org/GNOME/glib/-/merge_requests/4672>.
    ///
    /// Until this is fixed, it is unsafe to rely on the enumerator being closed when the object is dropped.
    /// It is recommended to close the enumerator explicitly before dropping it, by calling [`FileEnumeratorExt::close`],
    /// or to implement the [`ObjectImpl::dispose`] method and call [`FileEnumeratorExt::close`] there (it is safe to access the object there):
    /// ```ignore
    /// pub struct MyFileEnumerator();
    ///
    /// #[glib::object_subclass]
    /// impl ObjectSubclass for MyFileEnumerator { ... }
    ///
    /// impl ObjectImpl for MyFileEnumerator {
    ///     fn dispose(&self) {
    ///         // close the enumerator here is safe and avoids `finalize` to call close.
    ///         let _ = self.obj().close(Cancellable::NONE);
    ///     }
    /// }
    ///
    /// impl FileEnumeratorImpl for MyFileEnumerator { ... }
    /// ```
    ///
    /// [`FileEnumeratorExt::close`]: ../auto/file_enumerator/trait.FileEnumeratorExt.html#method.close
    /// [`ObjectImpl::dispose`]: ../../glib/subclass/object/trait.ObjectImpl.html#method.dispose
    fn close(&self, cancellable: Option<&Cancellable>) -> (bool, Option<glib::Error>) {
        self.parent_close(cancellable)
    }

    fn close_future(
        &self,
        io_priority: glib::Priority,
    ) -> Pin<Box<dyn Future<Output = Result<(), glib::Error>> + 'static>> {
        self.parent_close_future(io_priority)
    }
}

// Support parent implementation of virtual functions defined in `gio::ffi::GFileEnumeratorClass` except pairs `xxx_async/xxx_finish` for which GIO provides a default implementation (which should be ok).
// TODO: add parent implementation of `xxx_async/xxx_finish` virtual functions if overriding these default implementations is supported.
pub trait FileEnumeratorImplExt: FileEnumeratorImpl {
    fn parent_next_file(
        &self,
        cancellable: Option<&Cancellable>,
    ) -> Result<Option<FileInfo>, glib::Error> {
        if self.obj().is_closed() {
            Err(glib::Error::new::<IOErrorEnum>(
                IOErrorEnum::Closed,
                "Enumerator is closed",
            ))
        } else {
            unsafe {
                let data = Self::type_data();
                let parent_class = data.as_ref().parent_class() as *const ffi::GFileEnumeratorClass;

                let f = (*parent_class)
                    .next_file
                    .expect("No parent class implementation for \"next_file\"");

                let mut error = std::ptr::null_mut();
                let res = f(
                    self.obj()
                        .unsafe_cast_ref::<FileEnumerator>()
                        .to_glib_none()
                        .0,
                    cancellable.as_ref().to_glib_none().0,
                    &mut error,
                );
                if error.is_null() {
                    Ok(from_glib_full(res))
                } else {
                    Err(from_glib_full(error))
                }
            }
        }
    }

    fn parent_next_files_async<R: FnOnce(Result<glib::List<FileInfo>, glib::Error>) + 'static>(
        &self,
        num_files: i32,
        priority: glib::Priority,
        cancellable: Option<&Cancellable>,
        callback: R,
    ) {
        unsafe {
            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 data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *const ffi::GFileEnumeratorClass;

            let f = (*parent_class)
                .next_files_async
                .expect("No parent class implementation for \"next_files_async\"");
            let finish = (*parent_class)
                .next_files_finish
                .expect("no parent \"next_files_finish\" implementation");

            let user_data: Box<(glib::thread_guard::ThreadGuard<R>, _)> =
                Box::new((glib::thread_guard::ThreadGuard::new(callback), finish));

            unsafe extern "C" fn next_files_async_trampoline<
                R: FnOnce(Result<glib::List<FileInfo>, glib::Error>) + 'static,
            >(
                source_object_ptr: *mut glib::gobject_ffi::GObject,
                res: *mut ffi::GAsyncResult,
                user_data: glib::ffi::gpointer,
            ) {
                unsafe {
                    let mut error = std::ptr::null_mut();
                    let cb: Box<(
                        glib::thread_guard::ThreadGuard<R>,
                        fn(
                            *mut ffi::GFileEnumerator,
                            *mut ffi::GAsyncResult,
                            *mut *mut glib::ffi::GError,
                        ) -> *mut glib::ffi::GList,
                    )> = Box::from_raw(user_data as *mut _);
                    let ret = cb.1(source_object_ptr as _, res, &mut error);
                    let result = if error.is_null() {
                        Ok(glib::List::<FileInfo>::from_glib_full(ret))
                    } else {
                        Err(from_glib_full(error))
                    };
                    let cb = cb.0.into_inner();
                    cb(result);
                }
            }

            f(
                self.obj()
                    .unsafe_cast_ref::<FileEnumerator>()
                    .to_glib_none()
                    .0,
                num_files,
                priority.into_glib(),
                cancellable.to_glib_none().0,
                Some(next_files_async_trampoline::<R>),
                Box::into_raw(user_data) as *mut _,
            );
        }
    }

    fn parent_next_files_future(
        &self,
        num_files: i32,
        priority: glib::Priority,
    ) -> Pin<
        Box<dyn std::future::Future<Output = Result<glib::List<FileInfo>, glib::Error>> + 'static>,
    > {
        Box::pin(GioFuture::new(
            &self.ref_counted(),
            move |imp, cancellable, send| {
                imp.parent_next_files_async(num_files, priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    fn parent_close(&self, cancellable: Option<&Cancellable>) -> (bool, Option<glib::Error>) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *const ffi::GFileEnumeratorClass;

            let f = (*parent_class)
                .close_fn
                .expect("No parent class implementation for \"close_fn\"");

            let mut error = std::ptr::null_mut();
            let is_ok = f(
                self.obj()
                    .unsafe_cast_ref::<FileEnumerator>()
                    .to_glib_none()
                    .0,
                cancellable.as_ref().to_glib_none().0,
                &mut error,
            );
            (from_glib(is_ok), from_glib_full(error))
        }
    }

    fn parent_close_async<R: FnOnce(Result<(), glib::Error>) + 'static>(
        &self,
        io_priority: glib::Priority,
        cancellable: Option<&Cancellable>,
        callback: R,
    ) {
        unsafe {
            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 data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GFileEnumeratorClass;
            let f = (*parent_class)
                .close_async
                .expect("no parent \"close_async\" implementation");
            let finish = (*parent_class)
                .close_finish
                .expect("no parent \"close_finish\" implementation");

            let user_data: Box<(glib::thread_guard::ThreadGuard<R>, _)> =
                Box::new((glib::thread_guard::ThreadGuard::new(callback), finish));

            unsafe extern "C" fn close_async_trampoline<
                R: FnOnce(Result<(), glib::Error>) + 'static,
            >(
                source_object_ptr: *mut glib::gobject_ffi::GObject,
                res: *mut ffi::GAsyncResult,
                user_data: glib::ffi::gpointer,
            ) {
                unsafe {
                    let mut error = std::ptr::null_mut();
                    let cb: Box<(
                        glib::thread_guard::ThreadGuard<R>,
                        fn(
                            *mut ffi::GFileEnumerator,
                            *mut ffi::GAsyncResult,
                            *mut *mut glib::ffi::GError,
                        ) -> glib::ffi::gboolean,
                    )> = Box::from_raw(user_data as *mut _);
                    cb.1(source_object_ptr as _, res, &mut error);
                    let result = if error.is_null() {
                        Ok(())
                    } else {
                        Err(from_glib_full(error))
                    };
                    let cb = cb.0.into_inner();
                    cb(result);
                }
            }

            f(
                self.obj()
                    .unsafe_cast_ref::<FileEnumerator>()
                    .to_glib_none()
                    .0,
                io_priority.into_glib(),
                cancellable.to_glib_none().0,
                Some(close_async_trampoline::<R>),
                Box::into_raw(user_data) as *mut _,
            );
        }
    }

    fn parent_close_future(
        &self,
        io_priority: glib::Priority,
    ) -> Pin<Box<dyn Future<Output = Result<(), glib::Error>> + 'static>> {
        Box::pin(GioFuture::new(
            &self.ref_counted(),
            move |imp, cancellable, send| {
                imp.parent_close_async(io_priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }
}

impl<T: FileEnumeratorImpl> FileEnumeratorImplExt for T {}

// Implement virtual functions defined in `gio::ffi::GFileEnumeratorClass` except pairs `xxx_async/xxx_finish` for which GIO provides a default implementation.
unsafe impl<T: FileEnumeratorImpl> IsSubclassable<T> for FileEnumerator {
    fn class_init(class: &mut ::glib::Class<Self>) {
        Self::parent_class_init::<T>(class);

        let klass = class.as_mut();
        klass.next_file = Some(next_file::<T>);
        klass.close_fn = Some(close_fn::<T>);
        klass.next_files_async = Some(next_files_async::<T>);
        klass.next_files_finish = Some(next_files_finish);
        klass.close_async = Some(close_async::<T>);
        klass.close_finish = Some(close_finish);
    }
}

unsafe extern "C" fn next_file<T: FileEnumeratorImpl>(
    enumerator: *mut ffi::GFileEnumerator,
    cancellable: *mut ffi::GCancellable,
    error: *mut *mut glib::ffi::GError,
) -> *mut ffi::GFileInfo {
    unsafe {
        let instance = &*(enumerator as *mut T::Instance);
        let imp = instance.imp();
        let cancellable = Option::<Cancellable>::from_glib_none(cancellable);

        let res = imp.next_file(cancellable.as_ref());

        match res {
            Ok(fileinfo) => fileinfo.to_glib_full(),
            Err(err) => {
                if !error.is_null() {
                    *error = err.to_glib_full()
                }
                std::ptr::null_mut()
            }
        }
    }
}

unsafe extern "C" fn next_files_async<T: FileEnumeratorImpl>(
    enumerator: *mut ffi::GFileEnumerator,
    num_files: i32,
    priority: i32,
    cancellable: *mut ffi::GCancellable,
    callback: ffi::GAsyncReadyCallback,
    user_data: glib::ffi::gpointer,
) {
    unsafe {
        let instance = &*(enumerator as *mut T::Instance);
        let imp = instance.imp();
        let wrap: FileEnumerator = from_glib_none(enumerator);
        let cancellable: Option<Cancellable> = from_glib_none(cancellable);

        // Closure that will invoke the C callback when the LocalTask completes
        let closure = move |task: LocalTask<glib::ValueArray>,
                            source_object: Option<&glib::Object>| {
            let result: *mut ffi::GAsyncResult = task.upcast_ref::<AsyncResult>().to_glib_none().0;
            let source_object: *mut glib::gobject_ffi::GObject = source_object.to_glib_none().0;
            callback.unwrap()(source_object, result, user_data)
        };

        let t = LocalTask::new(
            Some(wrap.upcast_ref::<glib::Object>()),
            cancellable.as_ref(),
            closure,
        );

        // Spawn the async work on the main context
        glib::MainContext::ref_thread_default().spawn_local(async move {
            // Call the trait method's future version
            let res = imp.next_files_future(num_files, from_glib(priority)).await;

            // Store result in the task
            t.return_result(res.map(|files| {
                let values: Vec<glib::Value> = files
                    .into_iter()
                    .map(|file_info| file_info.to_value())
                    .collect();
                glib::ValueArray::from_values(values)
            }));
        });
    }
}

unsafe extern "C" fn next_files_finish(
    _enumerator: *mut ffi::GFileEnumerator,
    res_ptr: *mut ffi::GAsyncResult,
    error_ptr: *mut *mut glib::ffi::GError,
) -> *mut glib::ffi::GList {
    unsafe {
        let res: AsyncResult = from_glib_none(res_ptr);
        let t = res.downcast::<LocalTask<glib::ValueArray>>().unwrap();
        let ret = t.propagate();
        match ret {
            Ok(files) => {
                let files = files
                    .iter()
                    .map(|v| <FileInfo as glib::value::FromValue>::from_value(v))
                    .collect::<Vec<FileInfo>>();
                files.to_glib_full()
            }
            Err(e) => {
                if !error_ptr.is_null() {
                    *error_ptr = e.into_glib_ptr();
                }
                std::ptr::null_mut()
            }
        }
    }
}

unsafe extern "C" fn close_fn<T: FileEnumeratorImpl>(
    enumerator: *mut ffi::GFileEnumerator,
    cancellable: *mut ffi::GCancellable,
    error: *mut *mut glib::ffi::GError,
) -> glib::ffi::gboolean {
    unsafe {
        let instance = &*(enumerator as *mut T::Instance);
        let imp = instance.imp();
        let cancellable = Option::<Cancellable>::from_glib_none(cancellable);

        let res = imp.close(cancellable.as_ref());

        if !error.is_null() {
            *error = res.1.to_glib_full()
        }

        res.0.into_glib()
    }
}

unsafe extern "C" fn close_async<T: FileEnumeratorImpl>(
    enumerator: *mut ffi::GFileEnumerator,
    priority: i32,
    cancellable: *mut ffi::GCancellable,
    callback: ffi::GAsyncReadyCallback,
    user_data: glib::ffi::gpointer,
) {
    unsafe {
        let instance = &*(enumerator as *mut T::Instance);
        let imp = instance.imp();
        let wrap: FileEnumerator = from_glib_none(enumerator);
        let cancellable: Option<Cancellable> = from_glib_none(cancellable);

        // Closure that will invoke the C callback when the LocalTask completes
        let closure = move |task: LocalTask<bool>, source_object: Option<&glib::Object>| {
            let result: *mut ffi::GAsyncResult = task.upcast_ref::<AsyncResult>().to_glib_none().0;
            let source_object: *mut glib::gobject_ffi::GObject = source_object.to_glib_none().0;
            callback.unwrap()(source_object, result, user_data)
        };

        let t = LocalTask::new(
            Some(wrap.upcast_ref::<glib::Object>()),
            cancellable.as_ref(),
            closure,
        );

        // Spawn the async work on the main context
        glib::MainContext::ref_thread_default().spawn_local(async move {
            // Call the trait method's future version
            let res = imp.close_future(from_glib(priority)).await;

            // Store result in the task (bool indicates success/failure)
            t.return_result(res.map(|_t| true));
        });
    }
}

unsafe extern "C" fn close_finish(
    _enumerator: *mut ffi::GFileEnumerator,
    res_ptr: *mut ffi::GAsyncResult,
    error_ptr: *mut *mut glib::ffi::GError,
) -> glib::ffi::gboolean {
    unsafe {
        let res: AsyncResult = from_glib_none(res_ptr);
        let t = res.downcast::<LocalTask<bool>>().unwrap();
        match t.propagate() {
            Ok(_) => glib::ffi::GTRUE,
            Err(e) => {
                if !error_ptr.is_null() {
                    *error_ptr = e.into_glib_ptr();
                }
                glib::ffi::GFALSE
            }
        }
    }
}

#[cfg(test)]
mod tests {
    // The following tests rely on a custom type `MyCustomFileEnumerator` that extends another custom type `MyFileEnumerator`.
    // For each virtual method defined in class `gio::ffi::GFileEnumeratorClass`, a test checks that `MyCustomFileEnumerator` and `MyFileEnumerator` return the same results.

    use super::*;

    // Define `MyCustomFileEnumerator` as a subclass of `MyFileEnumerator`.
    mod imp {
        use std::cell::Cell;

        use super::*;

        #[derive(Default)]
        pub struct MyFileEnumerator(Cell<i32>);

        #[glib::object_subclass]
        impl ObjectSubclass for MyFileEnumerator {
            const NAME: &'static str = "MyFileEnumerator";
            type Type = super::MyFileEnumerator;
            type ParentType = FileEnumerator;
        }

        impl ObjectImpl for MyFileEnumerator {
            fn dispose(&self) {
                let _ = self.obj().close(Cancellable::NONE);
            }
        }

        // Implements `FileEnumeratorImpl` with custom implementation.
        impl FileEnumeratorImpl for MyFileEnumerator {
            fn next_file(
                &self,
                cancellable: Option<&Cancellable>,
            ) -> Result<Option<FileInfo>, glib::Error> {
                if cancellable.is_some_and(|c| c.is_cancelled()) {
                    Err(glib::Error::new::<IOErrorEnum>(
                        IOErrorEnum::Cancelled,
                        "Operation was cancelled",
                    ))
                } else {
                    match self.0.get() {
                        -1 => Err(glib::Error::new::<IOErrorEnum>(
                            IOErrorEnum::Closed,
                            "Enumerator is closed",
                        )),
                        i if i < 3 => {
                            let file_info = FileInfo::new();
                            file_info.set_display_name(&format!("file{i}"));
                            self.0.set(i + 1);
                            Ok(Some(file_info))
                        }
                        _ => Ok(None),
                    }
                }
            }

            fn next_files_future(
                &self,
                num_files: i32,
                _priority: glib::Priority,
            ) -> std::pin::Pin<
                Box<
                    dyn std::future::Future<Output = Result<glib::List<FileInfo>, glib::Error>>
                        + 'static,
                >,
            > {
                Box::pin(GioFuture::new(
                    &self.ref_counted(),
                    move |self_, cancellable, send| {
                        let mut res: Result<glib::List<FileInfo>, glib::Error> =
                            Ok(glib::List::new());
                        for _ in 0..num_files {
                            match self_.next_file(Some(cancellable)) {
                                Ok(Some(fi)) => res.as_mut().unwrap().push_back(fi),
                                Ok(None) => break,
                                Err(e) => {
                                    res = Err(e);
                                    break;
                                }
                            }
                        }
                        send.resolve(res);
                    },
                ))
            }

            fn close(&self, cancellable: Option<&Cancellable>) -> (bool, Option<glib::Error>) {
                if cancellable.is_some_and(|c| c.is_cancelled()) {
                    (
                        false,
                        Some(glib::Error::new::<IOErrorEnum>(
                            IOErrorEnum::Cancelled,
                            "Operation was cancelled",
                        )),
                    )
                } else {
                    self.0.set(-1);
                    (true, None)
                }
            }

            fn close_future(
                &self,
                _priority: glib::Priority,
            ) -> std::pin::Pin<
                Box<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>,
            > {
                Box::pin(GioFuture::new(
                    &self.ref_counted(),
                    move |self_, cancellable, send| {
                        let (is_ok, error) = self_.close(Some(cancellable));
                        debug_assert_eq!(!is_ok, error.is_some());
                        let res = if is_ok { Ok(()) } else { Err(error.unwrap()) };
                        send.resolve(res);
                    },
                ))
            }
        }

        #[derive(Default)]
        pub struct MyCustomFileEnumerator;

        #[glib::object_subclass]
        impl ObjectSubclass for MyCustomFileEnumerator {
            const NAME: &'static str = "MyCustomFileEnumerator";
            type Type = super::MyCustomFileEnumerator;
            type ParentType = super::MyFileEnumerator;
        }

        impl ObjectImpl for MyCustomFileEnumerator {}

        // Implements `FileEnumeratorImpl` with default implementation, which calls the parent's implementation.
        impl FileEnumeratorImpl for MyCustomFileEnumerator {}

        impl MyFileEnumeratorImpl for MyCustomFileEnumerator {}
    }

    glib::wrapper! {
        pub struct MyFileEnumerator(ObjectSubclass<imp::MyFileEnumerator>) @extends FileEnumerator;
    }

    pub trait MyFileEnumeratorImpl:
        ObjectImpl + ObjectSubclass<Type: IsA<MyFileEnumerator> + IsA<FileEnumerator>>
    {
    }

    // To make this class subclassable we need to implement IsSubclassable
    unsafe impl<T: MyFileEnumeratorImpl + FileEnumeratorImpl> IsSubclassable<T> for MyFileEnumerator {}

    glib::wrapper! {
        pub struct MyCustomFileEnumerator(ObjectSubclass<imp::MyCustomFileEnumerator>) @extends MyFileEnumerator, FileEnumerator;
    }

    #[test]
    fn file_enumerator_next_file() {
        // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file`
        let my_custom_file_enumerator = glib::Object::new::<MyCustomFileEnumerator>();
        let res = my_custom_file_enumerator.next_file(Cancellable::NONE);
        assert!(res.as_ref().is_ok_and(|res| res.is_some()));
        let filename = res.unwrap().unwrap().display_name();

        // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file`
        let my_file_enumerator = glib::Object::new::<MyFileEnumerator>();
        let res = my_file_enumerator.next_file(Cancellable::NONE);
        assert!(res.as_ref().is_ok_and(|res| res.is_some()));
        let expected = res.unwrap().unwrap().display_name();

        // both filenames should equal
        assert_eq!(filename, expected);

        // and also next results until there is no more file info
        for res in my_custom_file_enumerator.upcast::<FileEnumerator>() {
            assert!(res.as_ref().is_ok());
            let filename = res.unwrap().display_name();

            let res = my_file_enumerator.next_file(Cancellable::NONE);
            assert!(res.as_ref().is_ok_and(|res| res.is_some()));
            let expected = res.unwrap().unwrap().display_name();

            // both filenames should equal
            assert_eq!(filename, expected);
        }
    }

    #[test]
    fn file_enumerator_next_files_future() {
        // run test in a main context dedicated and configured as the thread default one
        let _ = glib::MainContext::new().with_thread_default(|| {
            // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_files_future` asynchronously
            let my_custom_file_enumerator = glib::Object::new::<MyCustomFileEnumerator>();
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_custom_file_enumerator.next_files_future(1, glib::Priority::DEFAULT));
            assert!(res.as_ref().is_ok_and(|res| res.len() == 1));
            let filename = res.unwrap().first().unwrap().display_name();

            // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_files_future` asynchronously
            let my_file_enumerator = glib::Object::new::<MyFileEnumerator>();
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_file_enumerator.next_files_future(1, glib::Priority::DEFAULT));
            assert!(res.as_ref().is_ok_and(|res| res.len() == 1));
            let expected = res.unwrap().first().unwrap().display_name();

            // both filenames should equal
            assert_eq!(filename, expected);

            // and also next results until there is no more file info
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_custom_file_enumerator.next_files_future(10, glib::Priority::DEFAULT));
            assert!(res.as_ref().is_ok());
            let filenames = res
                .unwrap()
                .into_iter()
                .map(|fi| fi.display_name())
                .collect::<Vec<_>>();

            let res = glib::MainContext::ref_thread_default()
                .block_on(my_file_enumerator.next_files_future(10, glib::Priority::DEFAULT));
            assert!(res.as_ref().is_ok());
            let expected = res
                .unwrap()
                .into_iter()
                .map(|fi| fi.display_name())
                .collect::<Vec<_>>();

            // both filenames should equal
            assert_eq!(filenames, expected);
        });
    }

    #[test]
    fn file_enumerator_close() {
        // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file`
        let my_custom_file_enumerator = glib::Object::new::<MyCustomFileEnumerator>();
        let res = my_custom_file_enumerator.next_file(Cancellable::NONE);
        assert!(res.as_ref().is_ok_and(|res| res.is_some()));
        let filename = res.unwrap().unwrap().display_name();

        // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file`
        let my_file_enumerator = glib::Object::new::<MyFileEnumerator>();
        let res = my_file_enumerator.next_file(Cancellable::NONE);
        assert!(res.as_ref().is_ok_and(|res| res.is_some()));
        let expected = res.unwrap().unwrap().display_name();

        // both filenames should equal
        assert_eq!(filename, expected);

        // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::close`
        let res = my_custom_file_enumerator.close(Cancellable::NONE);
        assert_eq!(res.1, None);
        let closed = res.0;

        // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::close`
        let res = my_file_enumerator.close(Cancellable::NONE);
        assert_eq!(res.1, None);
        let expected = res.0;

        // both results should equal
        assert_eq!(closed, expected);

        // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file`
        let res = my_custom_file_enumerator.next_file(Cancellable::NONE);
        assert!(res.is_err());
        let err = res.unwrap_err();

        // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file`
        let res = my_file_enumerator.next_file(Cancellable::NONE);
        assert!(res.is_err());
        let expected = res.unwrap_err();

        // both errors should equal
        assert_eq!(err.domain(), expected.domain());
        assert!(err.matches::<IOErrorEnum>(IOErrorEnum::Closed));
        assert!(expected.matches::<IOErrorEnum>(IOErrorEnum::Closed));
        assert_eq!(err.message(), expected.message());
    }

    #[test]
    fn file_enumerator_close_future() {
        // run test in a main context dedicated and configured as the thread default one
        let _ = glib::MainContext::new().with_thread_default(|| {
            // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_files_future` asynchronously
            let my_custom_file_enumerator = glib::Object::new::<MyCustomFileEnumerator>();
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_custom_file_enumerator.next_files_future(1, glib::Priority::DEFAULT));
            assert!(res.as_ref().is_ok_and(|res| res.len() == 1));
            let filename = res.unwrap().first().unwrap().display_name();

            // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_files_future` asynchronously
            let my_file_enumerator = glib::Object::new::<MyFileEnumerator>();
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_file_enumerator.next_files_future(1, glib::Priority::DEFAULT));
            assert!(res.as_ref().is_ok_and(|res| res.len() == 1));
            let expected = res.unwrap().first().unwrap().display_name();

            // both filenames should equal
            assert_eq!(filename, expected);

            // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::close_future` asynchronously
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_custom_file_enumerator.close_future(glib::Priority::DEFAULT));
            assert!(res.is_ok());
            let closed = true;

            // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::close_future` asynchronously
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_file_enumerator.close_future(glib::Priority::DEFAULT));
            assert!(res.is_ok());
            let expected = true;

            // both results should equal
            assert_eq!(closed, expected);

            // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_files_future` asynchronously
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_custom_file_enumerator.next_files_future(1, glib::Priority::DEFAULT));
            assert!(res.is_err());
            let err = res.unwrap_err();

            // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_files_future` asynchronously
            let res = glib::MainContext::ref_thread_default()
                .block_on(my_file_enumerator.next_files_future(1, glib::Priority::DEFAULT));
            assert!(res.is_err());
            let expected = res.unwrap_err();

            // both errors should equal
            assert_eq!(err.domain(), expected.domain());
            assert!(err.matches::<IOErrorEnum>(IOErrorEnum::Closed));
            assert!(expected.matches::<IOErrorEnum>(IOErrorEnum::Closed));
            assert_eq!(err.message(), expected.message());
        });
    }

    #[test]
    fn file_enumerator_cancel() {
        // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file`
        let my_custom_file_enumerator = glib::Object::new::<MyCustomFileEnumerator>();
        let res = my_custom_file_enumerator.next_file(Cancellable::NONE);
        assert!(res.as_ref().is_ok_and(|res| res.is_some()));
        let filename = res.unwrap().unwrap().display_name();

        // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file`
        let my_file_enumerator = glib::Object::new::<MyFileEnumerator>();
        let res = my_file_enumerator.next_file(Cancellable::NONE);
        assert!(res.as_ref().is_ok_and(|res| res.is_some()));
        let expected = res.unwrap().unwrap().display_name();

        // both filenames should equal
        assert_eq!(filename, expected);

        // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file` with cancel
        let cancellable = Cancellable::new();
        cancellable.cancel();
        let res = my_custom_file_enumerator.next_file(Some(&cancellable));
        assert!(res.as_ref().is_err());
        let err = res.unwrap_err();

        // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::next_file` with cancel
        let cancellable = Cancellable::new();
        cancellable.cancel();
        let res = my_file_enumerator.next_file(Some(&cancellable));
        assert!(res.as_ref().is_err());
        let expected = res.unwrap_err();

        // both errors should equal
        assert_eq!(err.domain(), expected.domain());
        assert!(err.matches::<IOErrorEnum>(IOErrorEnum::Cancelled));
        assert!(expected.matches::<IOErrorEnum>(IOErrorEnum::Cancelled));
        assert_eq!(err.message(), expected.message());

        // invoke `MyCustomFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::close` with cancel
        let cancellable = Cancellable::new();
        cancellable.cancel();
        let res = my_custom_file_enumerator.close(Some(&cancellable));
        assert!(res.1.is_some());
        let err = res.1.unwrap();

        // invoke `MyFileEnumerator` implementation of `gio::ffi::GFileEnumeratorClass::close` with cancel
        let cancellable = Cancellable::new();
        cancellable.cancel();
        let res = my_file_enumerator.close(Some(&cancellable));
        assert!(res.1.is_some());
        let expected = res.1.unwrap();

        // both errors should equal
        assert_eq!(err.domain(), expected.domain());
        assert!(err.matches::<IOErrorEnum>(IOErrorEnum::Cancelled));
        assert!(expected.matches::<IOErrorEnum>(IOErrorEnum::Cancelled));
        assert_eq!(err.message(), expected.message());
    }
}