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
use std::collections::BTreeMap;

use adw::subclass::prelude::*;
use gtk::{gio, glib, glib::clone, prelude::*};
use indexmap::IndexMap;
use ruma::{Int, OwnedUserId};

use super::MemberPowerLevel;
use crate::{
    session::model::{Permissions, PowerLevel, RemoteUser, User},
    spawn,
    utils::BoundObjectWeakRef,
};

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

    use super::*;

    #[derive(Debug, Default, glib::Properties)]
    #[properties(wrapper_type = super::PrivilegedMembers)]
    pub struct PrivilegedMembers {
        /// The list of members.
        pub list: RefCell<IndexMap<OwnedUserId, MemberPowerLevel>>,
        /// The permissions to watch.
        #[property(get, set = Self::set_permissions, construct_only)]
        pub permissions: BoundObjectWeakRef<Permissions>,
        /// Whether this list has changed.
        #[property(get)]
        pub changed: Cell<bool>,
    }

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

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

    impl ListModelImpl for PrivilegedMembers {
        fn item_type(&self) -> glib::Type {
            MemberPowerLevel::static_type()
        }

        fn n_items(&self) -> u32 {
            self.list.borrow().len() as u32
        }

        fn item(&self, position: u32) -> Option<glib::Object> {
            self.list
                .borrow()
                .get_index(position as usize)
                .map(|(_, member)| member.clone().upcast())
        }
    }

    impl PrivilegedMembers {
        /// Set the permissions to watch.
        fn set_permissions(&self, permissions: &Permissions) {
            let changed_handler =
                permissions.connect_changed(clone!(@weak self as imp => move |_| {
                    imp.update();
                }));
            self.permissions.set(permissions, vec![changed_handler]);

            self.update();
        }

        /// Update this list.
        fn update(&self) {
            let Some(permissions) = self.permissions.obj() else {
                return;
            };
            let Some(room) = permissions.room() else {
                return;
            };
            let Some(session) = room.session() else {
                return;
            };

            let members = room.get_or_create_members();
            let mut users = permissions.power_levels().users;

            let mut removed_users = Vec::new();
            {
                for user_id in self.list.borrow().keys() {
                    if !users.contains_key(user_id) {
                        removed_users.push(user_id.clone());
                        continue;
                    }

                    // Remove known members so only new members are left.
                    users.remove(user_id);
                }
            }

            for user_id in removed_users {
                self.remove_member(&user_id);
            }

            // Only new members are remaining.
            let mut new_handlers = Vec::with_capacity(users.len());
            let new_members = users.into_keys().map(|user_id| {
                let user = members
                    .get(&user_id)
                    .and_upcast::<User>()
                    .unwrap_or_else(|| {
                        let user = RemoteUser::new(&session, user_id.clone());

                        spawn!(clone!(@strong user => async move {
                            user.load_profile().await;
                        }));

                        user.upcast()
                    });
                let member = MemberPowerLevel::new(&user, &permissions);

                let handler =
                    member.connect_power_level_notify(clone!(@weak self as imp => move |_| {
                        imp.update_changed();
                    }));
                new_handlers.push(handler);

                (user_id, member)
            });

            self.add_members(new_members);
        }

        /// Remove the member with the given user ID from the list.
        fn remove_member(&self, user_id: &OwnedUserId) {
            let Some((pos, ..)) = self.list.borrow_mut().shift_remove_full(user_id) else {
                return;
            };

            self.obj().items_changed(pos as u32, 1, 0);
        }

        /// Add the given members to the list.
        pub(super) fn add_members(
            &self,
            members: impl ExactSizeIterator<Item = (OwnedUserId, MemberPowerLevel)>,
        ) {
            let pos = self.n_items();
            let added = members.len() as u32;

            self.list.borrow_mut().extend(members);

            self.update_changed();
            self.obj().items_changed(pos, 0, added);
        }

        /// Update whether the list has changed.
        fn update_changed(&self) {
            let changed = self.compute_changed();

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

            self.changed.set(changed);
            self.obj().notify_changed();
        }

        /// Compute whether the list has changed.
        fn compute_changed(&self) -> bool {
            let Some(permissions) = self.permissions.obj() else {
                return false;
            };

            let users = permissions.power_levels().users;
            let list = self.list.borrow();

            if users.len() != list.len() {
                return true;
            }

            for (user_id, member) in list.iter() {
                let Some(pl) = users.get(user_id) else {
                    // This is a new member.
                    return true;
                };

                if member.power_level() != PowerLevel::from(*pl) {
                    return true;
                }
            }

            false
        }
    }
}

glib::wrapper! {
    /// The list of members with custom power levels in a room.
    pub struct PrivilegedMembers(ObjectSubclass<imp::PrivilegedMembers>)
        @implements gio::ListModel;
}

impl PrivilegedMembers {
    /// Constructs a new `PrivilegedMembers` with the given permissions.
    pub fn new(permissions: &Permissions) -> Self {
        glib::Object::builder()
            .property("permissions", permissions)
            .build()
    }

    /// Add the given members to the list.
    pub fn add_members(
        &self,
        members: impl ExactSizeIterator<Item = (OwnedUserId, MemberPowerLevel)>,
    ) {
        let imp = self.imp();

        let mut new_members = Vec::with_capacity(members.len());

        {
            let list = imp.list.borrow();
            for (user_id, new_member) in members {
                if let Some(member) = list.get(&user_id) {
                    member.set_power_level(new_member.power_level());
                } else {
                    new_members.push((user_id, new_member));
                }
            }
        }

        if !new_members.is_empty() {
            self.imp().add_members(new_members.into_iter());
        }
    }

    /// Collect the list of members.
    pub fn collect(&self) -> BTreeMap<OwnedUserId, Int> {
        self.imp()
            .list
            .borrow()
            .values()
            .filter_map(|member| member.to_parts())
            .collect()
    }
}