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

use crate::utils::BoundObject;

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

    use super::*;

    #[derive(Debug, Default, glib::Properties)]
    #[properties(wrapper_type = super::ExpressionListModel)]
    pub struct ExpressionListModel {
        #[property(get)]
        pub model: BoundObject<gio::ListModel>,
        pub expressions: RefCell<Vec<gtk::Expression>>,
        pub watches: RefCell<Vec<Vec<gtk::ExpressionWatch>>>,
    }

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

    #[glib::derived_properties]
    impl ObjectImpl for ExpressionListModel {
        fn dispose(&self) {
            for watch in self.watches.take().iter().flatten() {
                watch.unwatch()
            }
        }
    }

    impl ListModelImpl for ExpressionListModel {
        fn item_type(&self) -> glib::Type {
            self.model
                .obj()
                .map(|m| m.item_type())
                .unwrap_or_else(glib::Object::static_type)
        }

        fn n_items(&self) -> u32 {
            self.model.obj().map(|m| m.n_items()).unwrap_or_default()
        }

        fn item(&self, position: u32) -> Option<glib::Object> {
            self.model.obj().and_then(|m| m.item(position))
        }
    }
}

glib::wrapper! {
    /// A list model that signals an item as changed when the expression's value changes.
    pub struct ExpressionListModel(ObjectSubclass<imp::ExpressionListModel>)
        @implements gio::ListModel;
}

impl ExpressionListModel {
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Set the underlying model.
    pub fn set_model(&self, model: Option<impl IsA<gio::ListModel>>) {
        let imp = self.imp();
        let model = model.and_upcast();

        let removed = self.n_items();

        imp.model.disconnect_signals();
        for watch in imp.watches.take().iter().flatten() {
            watch.unwatch();
        }

        let added = if let Some(model) = model {
            let items_changed_handler = model.connect_items_changed(clone!(
                #[strong(rename_to = obj)]
                self,
                move |_, pos, removed, added| {
                    obj.watch_items(pos, removed, added);
                    obj.items_changed(pos, removed, added);
                }
            ));

            let added = model.n_items();
            imp.model.set(model, vec![items_changed_handler]);

            self.watch_items(0, 0, added);
            added
        } else {
            0
        };

        self.items_changed(0, removed, added);
        self.notify_model();
    }

    /// The expressions to watch.
    pub fn expressions(&self) -> Vec<gtk::Expression> {
        self.imp().expressions.borrow().clone()
    }

    /// Set the expressions to watch.
    pub fn set_expressions(&self, expressions: Vec<gtk::Expression>) {
        let imp = self.imp();

        for watch in imp.watches.take().iter().flatten() {
            watch.unwatch();
        }

        imp.expressions.replace(expressions);
        self.watch_items(0, 0, self.n_items());
    }

    /// Watch and unwatch items according to changes in the underlying model.
    fn watch_items(&self, pos: u32, removed: u32, added: u32) {
        let Some(model) = self.model() else {
            return;
        };

        let expressions = self.expressions();
        if expressions.is_empty() {
            return;
        }

        let imp = self.imp();

        let mut new_watches = Vec::with_capacity(added as usize);
        for item_pos in pos..pos + added {
            let Some(item) = model.item(item_pos) else {
                error!("Out of bounds item");
                break;
            };

            let mut item_watches = Vec::with_capacity(expressions.len());
            for expression in &expressions {
                item_watches.push(expression.watch(
                    Some(&item),
                    clone!(
                        #[strong(rename_to = obj)]
                        self,
                        #[weak]
                        item,
                        move || {
                            obj.item_expr_changed(&item);
                        }
                    ),
                ));
            }

            new_watches.push(item_watches);
        }

        let mut watches = imp.watches.borrow_mut();
        let removed_range = (pos as usize)..((pos + removed) as usize);
        for watch in watches.splice(removed_range, new_watches).flatten() {
            watch.unwatch();
        }
    }

    fn item_expr_changed(&self, item: &glib::Object) {
        let Some(model) = self.model() else {
            return;
        };

        for (pos, obj) in model.snapshot().iter().enumerate() {
            if obj == item {
                self.items_changed(pos as u32, 1, 1);
                break;
            }
        }
    }
}

impl Default for ExpressionListModel {
    fn default() -> Self {
        Self::new()
    }
}