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

use crate::utils::BoundObjectWeakRef;

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

    use glib::subclass::InitializingObject;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(
        resource = "/org/gnome/Fractal/ui/session/view/content/room_details/addresses_subpage/completion_popover.ui"
    )]
    #[properties(wrapper_type = super::CompletionPopover)]
    pub struct CompletionPopover {
        #[template_child]
        pub list: TemplateChild<gtk::ListBox>,
        /// The parent entry to autocomplete.
        #[property(get, set = Self::set_entry, explicit_notify, nullable)]
        pub entry: BoundObjectWeakRef<gtk::Editable>,
        /// The key controller added to the parent entry.
        entry_controller: RefCell<Option<gtk::EventControllerKey>>,
        entry_binding: RefCell<Option<glib::Binding>>,
        /// The list model to use for completion.
        ///
        /// Only supports `GtkStringObject` items.
        #[property(get, set = Self::set_model, explicit_notify, nullable)]
        pub model: RefCell<Option<gio::ListModel>>,
        /// The string filter.
        #[property(get)]
        pub filter: gtk::StringFilter,
        /// The filtered list model.
        #[property(get)]
        pub filtered_list: gtk::FilterListModel,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for CompletionPopover {
        const NAME: &'static str = "RoomDetailsAddressesSubpageCompletionPopover";
        type Type = super::CompletionPopover;
        type ParentType = gtk::Popover;

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

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

    #[glib::derived_properties]
    impl ObjectImpl for CompletionPopover {
        fn constructed(&self) {
            self.parent_constructed();
            let obj = self.obj();

            self.filter
                .set_expression(Some(gtk::StringObject::this_expression("string")));
            self.filtered_list.set_filter(Some(&self.filter));

            self.filtered_list
                .connect_items_changed(clone!(@weak obj => move |_,_,_,_| {
                    obj.update_completion();
                }));

            self.list.bind_model(Some(&self.filtered_list), |item| {
                let Some(item) = item.downcast_ref::<gtk::StringObject>() else {
                    error!("Completion has item that is not a GtkStringObject");
                    return adw::Bin::new().upcast();
                };

                let label = gtk::Label::builder()
                    .label(item.string())
                    .ellipsize(pango::EllipsizeMode::End)
                    .halign(gtk::Align::Start)
                    .build();

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

        fn dispose(&self) {
            if let Some(entry) = self.entry.obj() {
                if let Some(controller) = self.entry_controller.take() {
                    entry.remove_controller(&controller)
                }
            }

            if let Some(binding) = self.entry_binding.take() {
                binding.unbind();
            }
        }
    }

    impl WidgetImpl for CompletionPopover {}
    impl PopoverImpl for CompletionPopover {}

    impl CompletionPopover {
        /// Set the parent entry to autocomplete.
        fn set_entry(&self, entry: Option<&gtk::Editable>) {
            let prev_entry = self.entry.obj();

            if prev_entry.as_ref() == entry {
                return;
            }
            let obj = self.obj();

            if let Some(entry) = prev_entry {
                if let Some(controller) = self.entry_controller.take() {
                    entry.remove_controller(&controller)
                }

                obj.unparent();
            }
            if let Some(binding) = self.entry_binding.take() {
                binding.unbind();
            }
            self.entry.disconnect_signals();

            if let Some(entry) = entry {
                let key_events = gtk::EventControllerKey::new();
                key_events.connect_key_pressed(clone!(@weak obj => @default-return glib::Propagation::Proceed, move |_, key, _, modifier| {
                    if modifier.is_empty() {
                        if obj.is_visible() {
                            let imp = obj.imp();
                            if matches!(key, gdk::Key::Return | gdk::Key::KP_Enter | gdk::Key::ISO_Enter) {
                                // Activate completion.
                                obj.activate_selected_row();
                                return glib::Propagation::Stop;
                            } else if matches!(key, gdk::Key::Up | gdk::Key::KP_Up) {
                                // Move up, if possible.
                                let idx = obj.selected_row_index().unwrap_or_default();
                                if idx > 0 {
                                    obj.select_row_at_index(Some(idx - 1));
                                }
                                return glib::Propagation::Stop;
                            } else if matches!(key, gdk::Key::Down | gdk::Key::KP_Down) {
                                // Move down, if possible.
                                let new_idx = if let Some(idx) = obj.selected_row_index() {
                                    idx + 1
                                } else {
                                    0
                                };
                                let max = imp.filtered_list.n_items() as usize;

                                if new_idx < max {
                                    obj.select_row_at_index(Some(new_idx));
                                }
                                return glib::Propagation::Stop;
                            } else if matches!(key, gdk::Key::Escape) {
                                // Close.
                                obj.popdown();
                                return glib::Propagation::Stop;
                            }
                        } else if matches!(key, gdk::Key::Tab) {
                            obj.update_completion();
                            return glib::Propagation::Stop;
                        }
                    }
                    glib::Propagation::Proceed
                }));

                entry.add_controller(key_events.clone());
                self.entry_controller.replace(Some(key_events));

                let search_binding = entry
                    .bind_property("text", &self.filter, "search")
                    .sync_create()
                    .build();
                self.entry_binding.replace(Some(search_binding));

                let changed_handler = entry.connect_changed(clone!(@weak obj => move |_| {
                    obj.update_completion();
                }));

                let state_flags_handler =
                    entry.connect_state_flags_changed(clone!(@weak obj => move |_, _| {
                        obj.update_completion();
                    }));

                obj.set_parent(entry);
                self.entry
                    .set(entry, vec![changed_handler, state_flags_handler]);
            }

            self.obj().notify_entry();
        }

        /// Set the list model to use for completion.
        fn set_model(&self, model: Option<gio::ListModel>) {
            if *self.model.borrow() == model {
                return;
            }

            self.filtered_list.set_model(model.as_ref());

            self.model.replace(model);
            self.obj().notify_model();
        }
    }
}

glib::wrapper! {
    /// A popover to auto-complete strings for a `gtk::Editable`.
    pub struct CompletionPopover(ObjectSubclass<imp::CompletionPopover>)
        @extends gtk::Widget, gtk::Popover, @implements gtk::Accessible;
}

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

    /// Update completion.
    fn update_completion(&self) {
        let Some(entry) = self.entry() else {
            return;
        };

        let imp = self.imp();
        let n_items = imp.filtered_list.n_items();

        // Always hide the popover if it's empty.
        if n_items == 0 {
            if self.is_visible() {
                self.popdown();
            }

            return;
        }

        // Always hide the popover if it has a single item that is exactly the text of
        // the entry.
        if n_items == 1 {
            if let Some(item) = imp
                .filtered_list
                .item(0)
                .and_downcast::<gtk::StringObject>()
            {
                if item.string() == entry.text() {
                    if self.is_visible() {
                        self.popdown();
                    }

                    return;
                }
            }
        }

        // Only show the popover if the entry is focused.
        let entry_has_focus = entry.state_flags().contains(gtk::StateFlags::FOCUS_WITHIN);
        if entry_has_focus {
            if !self.is_visible() {
                self.popup();
            }
        } else if self.is_visible() {
            self.popdown();
        }
    }

    fn selected_row_index(&self) -> Option<usize> {
        let imp = self.imp();

        let selected_text = self.selected_text()?;

        imp.filtered_list.iter::<glib::Object>().position(|o| {
            o.ok()
                .and_downcast::<gtk::StringObject>()
                .is_some_and(|o| o.string() == selected_text)
        })
    }

    fn select_row_at_index(&self, idx: Option<usize>) {
        let imp = self.imp();

        if self.selected_row_index() == idx || idx >= Some(imp.filtered_list.n_items() as usize) {
            return;
        }

        let imp = self.imp();

        if let Some(row) = idx.and_then(|idx| imp.list.row_at_index(idx as i32)) {
            imp.list.select_row(Some(&row));
        } else {
            imp.list.select_row(None::<&gtk::ListBoxRow>);
        }
    }

    /// The text of the selected row, if any.
    pub fn selected_text(&self) -> Option<glib::GString> {
        Some(
            self.imp()
                .list
                .selected_row()?
                .child()?
                .downcast_ref::<gtk::Label>()?
                .label(),
        )
    }

    /// Activate the selected row.
    ///
    /// Returns `true` if the row was activated.
    pub fn activate_selected_row(&self) -> bool {
        if !self.is_visible() {
            return false;
        }
        let Some(entry) = self.entry() else {
            return false;
        };

        let Some(selected_text) = self.selected_text() else {
            return false;
        };

        if selected_text == entry.text() {
            // Activating the row would have no effect.
            return false;
        }

        let Some(row) = self.imp().list.selected_row() else {
            return false;
        };

        row.activate();
        true
    }

    /// Handle a row being activated.
    #[template_callback]
    fn row_activated(&self, row: &gtk::ListBoxRow) {
        let Some(label) = row.child().and_downcast::<gtk::Label>() else {
            return;
        };
        let Some(entry) = self.entry() else {
            return;
        };

        entry.set_text(&label.label());

        self.popdown();
        entry.grab_focus();
    }
}

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