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

use crate::{
    components::{AtRoom, PillSource},
    session::model::{Member, MemberList, Membership},
    utils::{expression, ExpressionListModel},
};

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

    use super::*;

    #[derive(Debug, glib::Properties)]
    #[properties(wrapper_type = super::CompletionMemberList)]
    pub struct CompletionMemberList {
        /// The room members used for completion.
        #[property(get = Self::members, set = Self::set_members, explicit_notify, nullable)]
        members: PhantomData<Option<MemberList>>,
        /// The members list with expression watches.
        members_expr: ExpressionListModel,
        room_handler: RefCell<Option<glib::SignalHandlerId>>,
        permissions_handler: RefCell<Option<glib::SignalHandlerId>>,
        /// The list model for the `@room` item.
        at_room_model: gio::ListStore,
        /// The search filter.
        pub search_filter: gtk::StringFilter,
        /// The list of sorted and filtered room members.
        #[property(get)]
        pub list: gtk::FilterListModel,
    }

    impl Default for CompletionMemberList {
        fn default() -> Self {
            Self {
                members: Default::default(),
                members_expr: Default::default(),
                room_handler: Default::default(),
                permissions_handler: Default::default(),
                at_room_model: gio::ListStore::new::<AtRoom>(),
                search_filter: Default::default(),
                list: Default::default(),
            }
        }
    }

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

    #[glib::derived_properties]
    impl ObjectImpl for CompletionMemberList {
        fn constructed(&self) {
            self.parent_constructed();

            // Filter the members, the criteria:
            // - not our user
            // - not ignored
            // - joined
            let not_own_user = gtk::BoolFilter::builder()
                .expression(expression::not(Member::this_expression("is-own-user")))
                .build();

            let ignored_expr = Member::this_expression("is-ignored");
            let not_ignored = gtk::BoolFilter::builder()
                .expression(&ignored_expr)
                .invert(true)
                .build();

            let joined_expr = Member::this_expression("membership").chain_closure::<bool>(
                closure!(|_obj: Option<glib::Object>, membership: Membership| {
                    membership == Membership::Join
                }),
            );
            let joined = gtk::BoolFilter::new(Some(&joined_expr));

            let filter = gtk::EveryFilter::new();
            filter.append(not_own_user);
            filter.append(not_ignored);
            filter.append(joined);

            let first_model = gtk::FilterListModel::builder()
                .filter(&filter)
                .model(&self.members_expr)
                .build();

            // Sort the members list by activity, then display name.
            let latest_activity_expr = Member::this_expression("latest-activity");
            let activity = gtk::NumericSorter::builder()
                .sort_order(gtk::SortType::Descending)
                .expression(&latest_activity_expr)
                .build();

            let display_name_expr = Member::this_expression("display-name");
            let display_name = gtk::StringSorter::builder()
                .ignore_case(true)
                .expression(&display_name_expr)
                .build();

            let sorter = gtk::MultiSorter::new();
            sorter.append(activity);
            sorter.append(display_name);
            let sorted_members_model = gtk::SortListModel::builder()
                .sorter(&sorter)
                .model(&first_model)
                .build();

            // Add `@room` model.
            let models_list = gio::ListStore::new::<gio::ListModel>();
            models_list.append(&self.at_room_model);
            models_list.append(&sorted_members_model);
            let flatten_model = gtk::FlattenListModel::new(Some(models_list));

            // Setup the search filter.
            let item_search_string_expr = gtk::ClosureExpression::new::<String>(
                &[
                    PillSource::this_expression("identifier"),
                    PillSource::this_expression("display-name"),
                ],
                closure!(
                    |_: Option<glib::Object>, identifier: &str, display_name: &str| {
                        format!("{display_name} {identifier}")
                    }
                ),
            );
            self.search_filter.set_ignore_case(true);
            self.search_filter
                .set_match_mode(gtk::StringFilterMatchMode::Substring);
            self.search_filter
                .set_expression(Some(expression::normalize_string(item_search_string_expr)));

            self.list.set_filter(Some(&self.search_filter));
            self.list.set_model(Some(&flatten_model));

            self.members_expr.set_expressions(vec![
                ignored_expr.upcast(),
                joined_expr.upcast(),
                latest_activity_expr.upcast(),
                display_name_expr.upcast(),
            ]);
        }

        fn dispose(&self) {
            if let Some(room) = self.members().and_then(|m| m.room()) {
                if let Some(handler) = self.room_handler.take() {
                    room.disconnect(handler);
                }
                if let Some(handler) = self.permissions_handler.take() {
                    room.permissions().disconnect(handler);
                }
            }
        }
    }

    impl WidgetImpl for CompletionMemberList {}
    impl PopoverImpl for CompletionMemberList {}

    impl CompletionMemberList {
        /// The room members used for completion.
        fn members(&self) -> Option<MemberList> {
            self.members_expr.model().and_downcast()
        }

        /// Set the room members used for completion.
        fn set_members(&self, members: Option<MemberList>) {
            let prev_members = self.members();

            if prev_members == members {
                return;
            }

            if let Some(room) = prev_members.and_then(|m| m.room()) {
                if let Some(handler) = self.room_handler.take() {
                    room.disconnect(handler);
                }
                if let Some(handler) = self.permissions_handler.take() {
                    room.permissions().disconnect(handler);
                }
            }

            if let Some(room) = members.as_ref().and_then(|m| m.room()) {
                let room_handler =
                    room.connect_is_direct_notify(clone!(@weak self as imp => move |_| {
                        imp.update_at_room_model();
                    }));
                self.room_handler.replace(Some(room_handler));

                let permissions_handler = room.permissions().connect_can_notify_room_notify(
                    clone!(@weak self as imp => move |_| {
                        imp.update_at_room_model();
                    }),
                );
                self.permissions_handler.replace(Some(permissions_handler));
            }

            self.members_expr.set_model(members);
            self.update_at_room_model();
            self.obj().notify_members();
        }

        /// Update whether `@room` should be present in the suggestions.
        fn update_at_room_model(&self) {
            // Only present `@room` if it's not a DM and user can notify the room.
            let room = self
                .members()
                .and_then(|m| m.room())
                .filter(|r| !r.is_direct() && r.permissions().can_notify_room());

            if let Some(room) = room {
                if let Some(at_room) = self.at_room_model.item(0).and_downcast::<AtRoom>() {
                    if at_room.room_id() == room.room_id() {
                        return;
                    }

                    self.at_room_model.remove(0);
                }

                self.at_room_model.append(&room.at_room());
            } else if self.at_room_model.n_items() > 0 {
                self.at_room_model.remove(0);
            }
        }
    }
}

glib::wrapper! {
    /// The filtered and sorted members list for completion.
    ///
    /// Also includes an `@room` item for notifying the whole room.
    pub struct CompletionMemberList(ObjectSubclass<imp::CompletionMemberList>);
}

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

    /// Set the search term.
    pub fn set_search_term(&self, term: Option<&str>) {
        self.imp().search_filter.set_search(term);
    }
}

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