fractal/session/view/content/room_details/
edit_details_subpage.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
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
use adw::{prelude::*, subclass::prelude::*};
use gettextrs::gettext;
use gtk::{
    gio,
    glib::{self, clone},
    CompositeTemplate,
};
use matrix_sdk::RoomState;
use ruma::{assign, events::room::avatar::ImageInfo, OwnedMxcUri};
use tracing::error;

use crate::{
    components::{
        ActionButton, ActionState, AvatarData, AvatarImage, EditableAvatar, LoadingButton,
    },
    prelude::*,
    session::model::Room,
    spawn_tokio, toast,
    utils::{
        media::{image::ImageInfoLoader, FileInfo},
        template_callbacks::TemplateCallbacks,
        BoundObjectWeakRef, OngoingAsyncAction,
    },
};

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/edit_details_subpage.ui"
    )]
    #[properties(wrapper_type = super::EditDetailsSubpage)]
    pub struct EditDetailsSubpage {
        #[template_child]
        avatar: TemplateChild<EditableAvatar>,
        #[template_child]
        name_entry_row: TemplateChild<adw::EntryRow>,
        #[template_child]
        name_button: TemplateChild<ActionButton>,
        #[template_child]
        topic_text_view: TemplateChild<gtk::TextView>,
        #[template_child]
        topic_buffer: TemplateChild<gtk::TextBuffer>,
        #[template_child]
        save_topic_button: TemplateChild<LoadingButton>,
        /// The presented room.
        #[property(get, set = Self::set_room, explicit_notify, nullable)]
        room: BoundObjectWeakRef<Room>,
        changing_avatar: RefCell<Option<OngoingAsyncAction<OwnedMxcUri>>>,
        changing_name: RefCell<Option<OngoingAsyncAction<String>>>,
        changing_topic: RefCell<Option<OngoingAsyncAction<String>>>,
        expr_watch: RefCell<Option<gtk::ExpressionWatch>>,
    }

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

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

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

    #[glib::derived_properties]
    impl ObjectImpl for EditDetailsSubpage {
        fn dispose(&self) {
            self.disconnect_all();
        }
    }

    impl WidgetImpl for EditDetailsSubpage {}
    impl NavigationPageImpl for EditDetailsSubpage {}

    #[gtk::template_callbacks]
    impl EditDetailsSubpage {
        /// Set the presented room.
        fn set_room(&self, room: Option<&Room>) {
            let Some(room) = room else {
                // Just ignore when room is missing.
                return;
            };

            self.disconnect_all();

            let avatar_data = room.avatar_data();
            let expr_watch = AvatarData::this_expression("image")
                .chain_property::<AvatarImage>("uri-string")
                .watch(
                    Some(&avatar_data),
                    clone!(
                        #[weak(rename_to = imp)]
                        self,
                        #[weak]
                        avatar_data,
                        move || {
                            imp.avatar_changed(avatar_data.image().and_then(|i| i.uri()).as_ref());
                        }
                    ),
                );
            self.expr_watch.replace(Some(expr_watch));

            let name_handler = room.connect_name_notify(clone!(
                #[weak(rename_to = imp)]
                self,
                move |room| {
                    imp.name_changed(room.name().as_deref());
                }
            ));
            let topic_handler = room.connect_topic_notify(clone!(
                #[weak(rename_to = imp)]
                self,
                move |room| {
                    imp.topic_changed(room.topic().as_deref());
                }
            ));

            self.room.set(room, vec![name_handler, topic_handler]);
            self.obj().notify_room();
        }

        /// Handle when we receive an avatar URI change from the homeserver.
        fn avatar_changed(&self, uri: Option<&OwnedMxcUri>) {
            if let Some(action) = self.changing_avatar.borrow().as_ref() {
                if uri != action.as_value() {
                    // This is not the change we expected, maybe another device did a change too.
                    // Let's wait for another change.
                    return;
                }
            } else {
                // No action is ongoing, we don't need to do anything.
                return;
            };

            // Reset the state.
            self.changing_avatar.take();
            self.avatar.success();

            let obj = self.obj();
            if uri.is_none() {
                toast!(obj, gettext("Avatar removed successfully"));
            } else {
                toast!(obj, gettext("Avatar changed successfully"));
            }
        }

        /// Change the avatar.
        #[template_callback]
        async fn change_avatar(&self, file: gio::File) {
            let Some(room) = self.room.obj() else {
                return;
            };

            let matrix_room = room.matrix_room();
            if matrix_room.state() != RoomState::Joined {
                error!("Cannot change avatar of room not joined");
                return;
            }

            let obj = self.obj();
            let avatar = &self.avatar;
            avatar.edit_in_progress();

            let info = match FileInfo::try_from_file(&file).await {
                Ok(info) => info,
                Err(error) => {
                    error!("Could not load room avatar file info: {error}");
                    toast!(obj, gettext("Could not load file"));
                    avatar.reset();
                    return;
                }
            };

            let data = match file.load_contents_future().await {
                Ok((data, _)) => data,
                Err(error) => {
                    error!("Could not load room avatar file: {error}");
                    toast!(obj, gettext("Could not load file"));
                    avatar.reset();
                    return;
                }
            };

            let base_image_info = ImageInfoLoader::from(file).load_info().await;
            let image_info = assign!(ImageInfo::new(), {
                width: base_image_info.width,
                height: base_image_info.height,
                size: info.size.map(Into::into),
                mimetype: Some(info.mime.to_string()),
            });

            let Some(session) = room.session() else {
                return;
            };
            let client = session.client();
            let handle =
                spawn_tokio!(
                    async move { client.media().upload(&info.mime, data.into(), None).await }
                );

            let uri = match handle.await.unwrap() {
                Ok(res) => res.content_uri,
                Err(error) => {
                    error!("Could not upload room avatar: {error}");
                    toast!(obj, gettext("Could not upload avatar"));
                    avatar.reset();
                    return;
                }
            };

            let (action, weak_action) = OngoingAsyncAction::set(uri.clone());
            self.changing_avatar.replace(Some(action));

            let matrix_room = matrix_room.clone();
            let handle =
                spawn_tokio!(
                    async move { matrix_room.set_avatar_url(&uri, Some(image_info)).await }
                );

            // We don't need to handle the success of the request, we should receive the
            // change via sync.
            if let Err(error) = handle.await.unwrap() {
                // Because this action can finish in avatar_changed, we must only act if this is
                // still the current action.
                if weak_action.is_ongoing() {
                    self.changing_avatar.take();
                    error!("Could not change room avatar: {error}");
                    toast!(obj, gettext("Could not change avatar"));
                    avatar.reset();
                }
            }
        }

        /// Remove the avatar.
        #[template_callback]
        async fn remove_avatar(&self) {
            let Some(room) = self.room.obj() else {
                error!("Cannot remove avatar with missing room");
                return;
            };

            let matrix_room = room.matrix_room();
            if matrix_room.state() != RoomState::Joined {
                error!("Cannot remove avatar of room not joined");
                return;
            }

            let obj = self.obj();

            // Ask for confirmation.
            let confirm_dialog = adw::AlertDialog::builder()
                .default_response("cancel")
                .heading(gettext("Remove Avatar?"))
                .body(gettext(
                    "Do you really want to remove the avatar for this room?",
                ))
                .build();
            confirm_dialog.add_responses(&[
                ("cancel", &gettext("Cancel")),
                ("remove", &gettext("Remove")),
            ]);
            confirm_dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);

            if confirm_dialog.choose_future(&*obj).await != "remove" {
                return;
            }

            let avatar = &self.avatar;
            avatar.removal_in_progress();

            let (action, weak_action) = OngoingAsyncAction::remove();
            self.changing_avatar.replace(Some(action));

            let matrix_room = matrix_room.clone();
            let handle = spawn_tokio!(async move { matrix_room.remove_avatar().await });

            // We don't need to handle the success of the request, we should receive the
            // change via sync.
            if let Err(error) = handle.await.unwrap() {
                // Because this action can finish in avatar_changed, we must only act if this is
                // still the current action.
                if weak_action.is_ongoing() {
                    self.changing_avatar.take();
                    error!("Could not remove room avatar: {error}");
                    toast!(obj, gettext("Could not remove avatar"));
                    avatar.reset();
                }
            }
        }

        /// Reset the name entry and button.
        fn reset_name(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            self.name_entry_row
                .set_sensitive(room.permissions().can_change_name());
            self.name_entry_row
                .set_text(&room.name().unwrap_or_default());
            self.name_button.set_visible(false);
            self.name_button.set_state(ActionState::Confirm);
        }

        /// Handle when we receive a name change from the homeserver.
        fn name_changed(&self, name: Option<&str>) {
            if let Some(action) = self.changing_name.borrow().as_ref() {
                if name != action.as_value().map(String::as_str) {
                    // This is not the change we expected, maybe another device did a change too.
                    // Let's wait for another change.
                    return;
                }
            } else {
                // No action is ongoing, we don't need to do anything.
                return;
            };

            let obj = self.obj();
            toast!(obj, gettext("Room name saved successfully"));

            // Reset state.
            self.changing_name.take();
            self.reset_name();
        }

        /// Whether the room name was edited.
        fn was_name_edited(&self) -> bool {
            let Some(room) = self.room.obj() else {
                return false;
            };

            let text = Some(self.name_entry_row.text()).filter(|t| !t.is_empty());
            // Do not send text if it has just more whitespaces at the beginning or end.
            let trimmed_text = text.as_deref().map(str::trim).filter(|t| !t.is_empty());

            let name = room.name();
            name.as_deref() != text.as_deref() && name.as_deref() != trimmed_text
        }

        /// Handle when the name was edited in the entry.
        #[template_callback]
        fn name_edited(&self) {
            self.name_button.set_visible(self.was_name_edited());
        }

        /// Change the name of the room.
        #[template_callback]
        async fn change_name(&self) {
            if !self.was_name_edited() {
                // No change to send.
                return;
            }

            let Some(room) = self.room.obj() else {
                return;
            };

            let matrix_room = room.matrix_room().clone();
            if matrix_room.state() != RoomState::Joined {
                error!("Cannot change name of room not joined");
                return;
            }

            self.name_entry_row.set_sensitive(false);
            self.name_button.set_state(ActionState::Loading);

            // Trim whitespaces.
            let name = Some(self.name_entry_row.text().trim())
                .filter(|t| !t.is_empty())
                .map(ToOwned::to_owned);

            let (action, weak_action) = if let Some(name) = name.clone() {
                OngoingAsyncAction::set(name)
            } else {
                OngoingAsyncAction::remove()
            };
            self.changing_name.replace(Some(action));

            let handle =
                spawn_tokio!(async move { matrix_room.set_name(name.unwrap_or_default()).await });

            // We don't need to handle the success of the request, we should receive the
            // change via sync.
            if let Err(error) = handle.await.unwrap() {
                // Because this action can finish in name_changed, we must only act if this is
                // still the current action.
                if weak_action.is_ongoing() {
                    self.changing_name.take();
                    error!("Could not change room name: {error}");
                    let obj = self.obj();
                    toast!(obj, gettext("Could not change room name"));
                    self.name_entry_row.set_sensitive(true);
                    self.name_button.set_state(ActionState::Retry);
                }
            }
        }

        /// Reset the topic text view and button.
        fn reset_topic(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            self.topic_text_view
                .set_sensitive(room.permissions().can_change_topic());
            self.topic_buffer
                .set_text(&room.topic().unwrap_or_default());
            self.save_topic_button.set_is_loading(false);
            self.save_topic_button.set_sensitive(false);
        }

        /// Handle when we receive a topic change from the homeserver.
        fn topic_changed(&self, topic: Option<&str>) {
            // It is not possible to remove a topic so we process the empty string as
            // `None`. We need to cancel that here.
            let topic = topic.unwrap_or_default();

            if let Some(action) = self.changing_topic.borrow().as_ref() {
                if Some(topic) != action.as_value().map(String::as_str) {
                    // This is not the change we expected, maybe another device did a change too.
                    // Let's wait for another change.
                    return;
                }
            } else {
                // No action is ongoing, we don't need to do anything.
                return;
            };

            let obj = self.obj();
            toast!(obj, gettext("Room description saved successfully"));

            // Reset state.
            self.changing_topic.take();
            self.reset_topic();
        }

        /// Whether the room topic was edited.
        fn was_topic_edited(&self) -> bool {
            let Some(room) = self.room.obj() else {
                return false;
            };

            let (start_iter, end_iter) = self.topic_buffer.bounds();
            let text = Some(self.topic_buffer.text(&start_iter, &end_iter, false))
                .filter(|t| !t.is_empty());
            // Do not send text if it has just more whitespaces at the beginning or end.
            let trimmed_text = text.as_deref().map(str::trim).filter(|t| !t.is_empty());

            let topic = room.topic();
            topic.as_deref() != text.as_deref() && topic.as_deref() != trimmed_text
        }

        /// Handle when the topic was edited in the text view.
        #[template_callback]
        fn topic_edited(&self) {
            self.save_topic_button
                .set_sensitive(self.was_topic_edited());
        }

        /// Change the topic of the room.
        #[template_callback]
        async fn change_topic(&self) {
            if !self.was_topic_edited() {
                // No change to send.
                return;
            }

            let Some(room) = self.room.obj() else {
                return;
            };

            let matrix_room = room.matrix_room().clone();
            if matrix_room.state() != RoomState::Joined {
                error!("Cannot change description of room not joined");
                return;
            }

            self.topic_text_view.set_sensitive(false);
            self.save_topic_button.set_is_loading(true);

            // Trim whitespaces.
            let (start_iter, end_iter) = self.topic_buffer.bounds();
            let topic = Some(self.topic_buffer.text(&start_iter, &end_iter, false).trim())
                .filter(|t| !t.is_empty())
                .map(ToOwned::to_owned);

            let (action, weak_action) = if let Some(topic) = topic.clone() {
                OngoingAsyncAction::set(topic)
            } else {
                OngoingAsyncAction::remove()
            };
            self.changing_topic.replace(Some(action));

            let handle = spawn_tokio!(async move {
                matrix_room.set_room_topic(&topic.unwrap_or_default()).await
            });

            // We don't need to handle the success of the request, we should receive the
            // change via sync.
            if let Err(error) = handle.await.unwrap() {
                // Because this action can finish in topic_changed, we must only act if this is
                // still the current action.
                if weak_action.is_ongoing() {
                    self.changing_topic.take();
                    error!("Could not change room description: {error}");
                    let obj = self.obj();
                    toast!(obj, gettext("Could not change room description"));
                    self.topic_text_view.set_sensitive(true);
                    self.save_topic_button.set_is_loading(false);
                }
            }
        }

        /// Go back to the previous page in the room details.
        ///
        /// If there are changes in the page, ask the user to confirm.
        #[template_callback]
        async fn go_back(&self) {
            let obj = self.obj();
            let mut reset_after = false;

            let has_unsaved_changes = (self.was_name_edited()
                && self.changing_name.borrow().is_none())
                || (self.was_topic_edited() && self.changing_topic.borrow().is_none());

            if has_unsaved_changes {
                let title = gettext("Discard Unsaved Changes?");
                let description = gettext(
                    "This page contains unsaved changes. Changes which are not saved will be lost.",
                );
                let dialog = adw::AlertDialog::builder()
                    .title(title)
                    .body(description)
                    .default_response("cancel")
                    .build();

                dialog.add_responses(&[
                    ("cancel", &gettext("Cancel")),
                    ("discard", &gettext("Discard")),
                ]);
                dialog.set_response_appearance("discard", adw::ResponseAppearance::Destructive);

                match dialog.choose_future(&*obj).await.as_str() {
                    "discard" => {
                        reset_after = true;
                    }
                    _ => {
                        return;
                    }
                }
            }

            obj.activate_action("navigation.pop", None).unwrap();

            if reset_after {
                self.reset_name();
                self.reset_topic();
            }
        }

        /// Disconnect all the signals.
        fn disconnect_all(&self) {
            self.room.disconnect_signals();

            if let Some(watch) = self.expr_watch.take() {
                watch.unwatch();
            }
        }
    }
}

glib::wrapper! {
    /// Subpage to edit the room main details (avatar, name and topic).
    pub struct EditDetailsSubpage(ObjectSubclass<imp::EditDetailsSubpage>)
        @extends gtk::Widget, adw::NavigationPage, @implements gtk::Accessible;
}

impl EditDetailsSubpage {
    /// Construct a new `EditDetailsSubpage` for the given room.
    pub fn new(room: &Room) -> Self {
        glib::Object::builder().property("room", room).build()
    }
}