fractal/components/rows/
combo_loading_row.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
use adw::{prelude::*, subclass::prelude::*};
use gtk::{glib, glib::clone, pango, CompositeTemplate};

use crate::{components::LoadingBin, utils::BoundObject};

mod imp {
    use std::{
        cell::{Cell, RefCell},
        marker::PhantomData,
    };

    use glib::subclass::InitializingObject;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(resource = "/org/gnome/Fractal/ui/components/rows/combo_loading_row.ui")]
    #[properties(wrapper_type = super::ComboLoadingRow)]
    pub struct ComboLoadingRow {
        #[template_child]
        pub loading_bin: TemplateChild<LoadingBin>,
        #[template_child]
        pub popover: TemplateChild<gtk::Popover>,
        #[template_child]
        pub list: TemplateChild<gtk::ListBox>,
        /// The string model to build the list.
        #[property(get, set = Self::set_string_model, explicit_notify, nullable)]
        pub string_model: BoundObject<gtk::StringList>,
        /// The position of the selected string.
        #[property(get, default = gtk::INVALID_LIST_POSITION)]
        pub selected: Cell<u32>,
        /// The selected string.
        #[property(get, set = Self::set_selected_string, explicit_notify, nullable)]
        pub selected_string: RefCell<Option<String>>,
        /// Whether the row is loading.
        #[property(get = Self::is_loading, set = Self::set_is_loading)]
        pub is_loading: PhantomData<bool>,
        /// Whether the row is read-only.
        #[property(get, set = Self::set_read_only, explicit_notify)]
        pub read_only: Cell<bool>,
        selected_handlers: RefCell<Vec<glib::SignalHandlerId>>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for ComboLoadingRow {
        const NAME: &'static str = "ComboLoadingRow";
        type Type = super::ComboLoadingRow;
        type ParentType = adw::ActionRow;

        fn class_init(klass: &mut Self::Class) {
            Self::bind_template(klass);
            Self::Type::bind_template_callbacks(klass);

            klass.set_accessible_role(gtk::AccessibleRole::ComboBox);
        }

        fn instance_init(obj: &InitializingObject<Self>) {
            obj.init_template();
        }
    }

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

    impl WidgetImpl for ComboLoadingRow {}
    impl ListBoxRowImpl for ComboLoadingRow {}
    impl PreferencesRowImpl for ComboLoadingRow {}

    impl ActionRowImpl for ComboLoadingRow {
        fn activate(&self) {
            if !self.is_loading() {
                self.popover.popup();
            }
        }
    }

    impl ComboLoadingRow {
        /// Set the string model to build the list.
        fn set_string_model(&self, model: Option<gtk::StringList>) {
            if self.string_model.obj() == model {
                return;
            }
            let obj = self.obj();

            for handler in self.selected_handlers.take() {
                obj.disconnect(handler);
            }
            self.string_model.disconnect_signals();

            self.list.bind_model(
                model.as_ref(),
                clone!(
                    #[weak]
                    obj,
                    #[upgrade_or_else]
                    || { gtk::ListBoxRow::new().upcast() },
                    move |item| {
                        let Some(item) = item.downcast_ref::<gtk::StringObject>() else {
                            return gtk::ListBoxRow::new().upcast();
                        };

                        let string = item.string();
                        let child = gtk::Box::new(gtk::Orientation::Horizontal, 6);

                        let label = gtk::Label::builder()
                            .xalign(0.0)
                            .ellipsize(pango::EllipsizeMode::End)
                            .max_width_chars(40)
                            .valign(gtk::Align::Center)
                            .label(string)
                            .build();
                        child.append(&label);

                        let icon = gtk::Image::builder()
                            .accessible_role(gtk::AccessibleRole::Presentation)
                            .icon_name("object-select-symbolic")
                            .build();

                        let selected_handler = obj.connect_selected_string_notify(clone!(
                            #[weak]
                            label,
                            #[weak]
                            icon,
                            move |obj| {
                                let is_selected =
                                    obj.selected_string().is_some_and(|s| s == label.label());
                                let opacity = if is_selected { 1.0 } else { 0.0 };
                                icon.set_opacity(opacity);
                            }
                        ));
                        obj.imp()
                            .selected_handlers
                            .borrow_mut()
                            .push(selected_handler);

                        let is_selected = obj.selected_string().is_some_and(|s| s == label.label());
                        let opacity = if is_selected { 1.0 } else { 0.0 };
                        icon.set_opacity(opacity);
                        child.append(&icon);

                        gtk::ListBoxRow::builder().child(&child).build().upcast()
                    }
                ),
            );

            if let Some(model) = model {
                let items_changed_handler = model.connect_items_changed(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_, _, _, _| {
                        imp.update_selected();
                    }
                ));

                self.string_model.set(model, vec![items_changed_handler]);
            }

            self.update_selected();
            obj.notify_string_model();
        }

        /// Set whether the row is loading.
        fn set_selected_string(&self, string: Option<String>) {
            if *self.selected_string.borrow() == string {
                return;
            }
            let obj = self.obj();

            obj.set_subtitle(string.as_deref().unwrap_or_default());
            self.selected_string.replace(string);

            self.update_selected();
            obj.notify_selected_string();
        }

        /// Update the position of the selected string.
        fn update_selected(&self) {
            let mut selected = gtk::INVALID_LIST_POSITION;

            if let Some((string_model, selected_string)) = self
                .string_model
                .obj()
                .zip(self.selected_string.borrow().clone())
            {
                for (pos, item) in string_model.iter::<glib::Object>().enumerate() {
                    let Some(item) = item.ok().and_downcast::<gtk::StringObject>() else {
                        // The iterator is broken.
                        break;
                    };

                    if item.string() == selected_string {
                        selected = pos as u32;
                        break;
                    }
                }
            }

            if self.selected.get() == selected {
                return;
            }

            self.selected.set(selected);
            self.obj().notify_selected();
        }

        /// Whether the row is loading.
        fn is_loading(&self) -> bool {
            self.loading_bin.is_loading()
        }

        /// Set whether the row is loading.
        fn set_is_loading(&self, loading: bool) {
            if self.is_loading() == loading {
                return;
            }

            self.loading_bin.set_is_loading(loading);
            self.obj().notify_is_loading();
        }

        /// Set whether the row is read-only.
        fn set_read_only(&self, read_only: bool) {
            if self.read_only.get() == read_only {
                return;
            }
            let obj = self.obj();

            self.read_only.set(read_only);

            obj.update_property(&[gtk::accessible::Property::ReadOnly(read_only)]);
            obj.notify_read_only();
        }
    }
}

glib::wrapper! {
    /// An `AdwActionRow` behaving like a combo box, with a loading state.
    pub struct ComboLoadingRow(ObjectSubclass<imp::ComboLoadingRow>)
        @extends gtk::Widget, gtk::ListBoxRow, adw::PreferencesRow, adw::ActionRow,
        @implements gtk::Actionable, gtk::Accessible;
}

#[gtk::template_callbacks]
impl ComboLoadingRow {
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// A row was activated.
    #[template_callback]
    fn row_activated(&self, row: &gtk::ListBoxRow) {
        let Some(string) = row
            .child()
            .and_downcast::<gtk::Box>()
            .and_then(|b| b.first_child())
            .and_downcast::<gtk::Label>()
            .map(|l| l.label())
        else {
            return;
        };

        self.imp().popover.popdown();
        self.set_selected_string(Some(string));
    }

    /// The popover's visibility changed.
    #[template_callback]
    fn popover_visible(&self) {
        let is_visible = self.imp().popover.is_visible();

        if is_visible {
            self.add_css_class("has-open-popup");
        } else {
            self.remove_css_class("has-open-popup");
        }
    }
}