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
use gtk::{gio, glib, prelude::*, subclass::prelude::*};

mod imp {
    use std::cell::OnceCell;

    use super::*;

    #[derive(Debug, Default, glib::Properties)]
    #[properties(wrapper_type = super::SingleItemListModel)]
    pub struct SingleItemListModel {
        /// The item contained by this model.
        #[property(get, construct_only)]
        pub inner_item: OnceCell<glib::Object>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for SingleItemListModel {
        const NAME: &'static str = "SingleItemListModel";
        type Type = super::SingleItemListModel;
        type Interfaces = (gio::ListModel,);
    }

    #[glib::derived_properties]
    impl ObjectImpl for SingleItemListModel {}

    impl ListModelImpl for SingleItemListModel {
        fn item_type(&self) -> glib::Type {
            self.inner_item().type_()
        }

        fn n_items(&self) -> u32 {
            1
        }

        fn item(&self, position: u32) -> Option<glib::Object> {
            (position == 0).then(|| self.inner_item().clone().upcast())
        }
    }

    impl SingleItemListModel {
        /// The item contained by this model.
        fn inner_item(&self) -> &glib::Object {
            self.inner_item.get().unwrap()
        }
    }
}

glib::wrapper! {
    /// A list model always containing a single item.
    pub struct SingleItemListModel(ObjectSubclass<imp::SingleItemListModel>)
        @implements gio::ListModel;
}

impl SingleItemListModel {
    /// Construct a new `SingleItemListModel` for the given item.
    pub fn new(item: &impl IsA<glib::Object>) -> Self {
        glib::Object::builder().property("inner-item", item).build()
    }
}