fractal/session/view/content/room_details/
general_page.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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
use adw::{prelude::*, subclass::prelude::*};
use gettextrs::{gettext, ngettext};
use gtk::{
    gio,
    glib::{self, clone},
    pango, CompositeTemplate,
};
use ruma::{
    api::client::{
        directory::{get_room_visibility, set_room_visibility},
        discovery::get_capabilities::Capabilities,
        room::{upgrade_room, Visibility},
    },
    events::{
        room::{
            guest_access::{GuestAccess, RoomGuestAccessEventContent},
            history_visibility::RoomHistoryVisibilityEventContent,
            power_levels::PowerLevelAction,
        },
        StateEventType,
    },
};
use tracing::error;

use super::{room_upgrade_dialog::confirm_room_upgrade, MemberRow, MembershipLists, RoomDetails};
use crate::{
    components::{
        ButtonCountRow, CheckLoadingRow, ComboLoadingRow, CopyableRow, LoadingButton,
        SwitchLoadingRow,
    },
    gettext_f,
    prelude::*,
    session::model::{
        HistoryVisibilityValue, JoinRuleValue, Member, NotificationsRoomSetting, Room, RoomCategory,
    },
    spawn, spawn_tokio, toast,
    utils::{
        expression, matrix::MatrixIdUri, template_callbacks::TemplateCallbacks, BoundObjectWeakRef,
        OngoingAsyncAction,
    },
    Window,
};

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/session/view/content/room_details/general_page.ui"
    )]
    #[properties(wrapper_type = super::GeneralPage)]
    pub struct GeneralPage {
        #[template_child]
        pub room_topic: TemplateChild<gtk::Label>,
        #[template_child]
        pub edit_details_btn: TemplateChild<gtk::Button>,
        #[template_child]
        pub direct_members_group: TemplateChild<adw::PreferencesGroup>,
        #[template_child]
        pub direct_members_list: TemplateChild<gtk::ListBox>,
        #[template_child]
        pub no_direct_members_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub members_row_group: TemplateChild<adw::PreferencesGroup>,
        #[template_child]
        pub members_row: TemplateChild<ButtonCountRow>,
        #[template_child]
        pub notifications: TemplateChild<adw::PreferencesGroup>,
        #[template_child]
        pub notifications_global_row: TemplateChild<CheckLoadingRow>,
        #[template_child]
        pub notifications_all_row: TemplateChild<CheckLoadingRow>,
        #[template_child]
        pub notifications_mentions_row: TemplateChild<CheckLoadingRow>,
        #[template_child]
        pub notifications_mute_row: TemplateChild<CheckLoadingRow>,
        #[template_child]
        pub addresses_group: TemplateChild<adw::PreferencesGroup>,
        #[template_child]
        pub edit_addresses_button: TemplateChild<gtk::Button>,
        #[template_child]
        pub no_addresses_label: TemplateChild<gtk::Label>,
        pub canonical_alias_row: RefCell<Option<CopyableRow>>,
        pub alt_aliases_rows: RefCell<Vec<CopyableRow>>,
        #[template_child]
        pub join_rule: TemplateChild<ComboLoadingRow>,
        #[template_child]
        pub guest_access: TemplateChild<SwitchLoadingRow>,
        #[template_child]
        pub publish: TemplateChild<SwitchLoadingRow>,
        #[template_child]
        pub history_visibility: TemplateChild<ComboLoadingRow>,
        #[template_child]
        pub encryption: TemplateChild<SwitchLoadingRow>,
        #[template_child]
        pub upgrade_button: TemplateChild<LoadingButton>,
        #[template_child]
        pub room_federated: TemplateChild<adw::ActionRow>,
        /// The presented room.
        #[property(get, set = Self::set_room, construct_only)]
        room: BoundObjectWeakRef<Room>,
        /// The lists of members filtered by membership for the room.
        #[property(get, set = Self::set_membership_lists, construct_only)]
        membership_lists: glib::WeakRef<MembershipLists>,
        /// The notifications setting for the room.
        #[property(get = Self::notifications_setting, set = Self::set_notifications_setting, explicit_notify, builder(NotificationsRoomSetting::default()))]
        pub notifications_setting: PhantomData<NotificationsRoomSetting>,
        /// Whether the notifications section is busy.
        #[property(get)]
        pub notifications_loading: Cell<bool>,
        /// Whether the room is published in the directory.
        #[property(get)]
        pub is_published: Cell<bool>,
        pub changing_avatar: RefCell<Option<OngoingAsyncAction<String>>>,
        pub changing_name: RefCell<Option<OngoingAsyncAction<String>>>,
        pub changing_topic: RefCell<Option<OngoingAsyncAction<String>>>,
        pub expr_watch: RefCell<Option<gtk::ExpressionWatch>>,
        pub notifications_settings_handlers: RefCell<Vec<glib::SignalHandlerId>>,
        pub membership_handler: RefCell<Option<glib::SignalHandlerId>>,
        pub permissions_handler: RefCell<Option<glib::SignalHandlerId>>,
        pub canonical_alias_handler: RefCell<Option<glib::SignalHandlerId>>,
        pub alt_aliases_handler: RefCell<Option<glib::SignalHandlerId>>,
        pub join_rule_handler: RefCell<Option<glib::SignalHandlerId>>,
        pub capabilities: RefCell<Capabilities>,
        direct_members_list_has_bound_model: Cell<bool>,
    }

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

        fn class_init(klass: &mut Self::Class) {
            CopyableRow::ensure_type();

            Self::bind_template(klass);
            Self::Type::bind_template_callbacks(klass);
            TemplateCallbacks::bind_template_callbacks(klass);

            klass
                .install_property_action("room.set-notifications-setting", "notifications-setting");
        }

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

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

            self.room_topic.connect_activate_link(clone!(
                #[weak]
                obj,
                #[upgrade_or]
                glib::Propagation::Proceed,
                move |_, uri| {
                    let Ok(uri) = MatrixIdUri::parse(uri) else {
                        return glib::Propagation::Proceed;
                    };
                    let Some(room_details) = obj
                        .ancestor(RoomDetails::static_type())
                        .and_downcast::<RoomDetails>()
                    else {
                        return glib::Propagation::Proceed;
                    };
                    let Some(parent_window) = room_details.transient_for().and_downcast::<Window>()
                    else {
                        return glib::Propagation::Proceed;
                    };

                    parent_window.session_view().show_matrix_uri(uri);
                    room_details.close();

                    glib::Propagation::Stop
                }
            ));
        }

        fn dispose(&self) {
            self.disconnect_all();
        }
    }

    impl WidgetImpl for GeneralPage {}
    impl PreferencesPageImpl for GeneralPage {}

    impl GeneralPage {
        /// Set the presented room.
        #[allow(clippy::too_many_lines)]
        fn set_room(&self, room: &Room) {
            let obj = self.obj();

            let membership_handler = room.own_member().connect_membership_notify(clone!(
                #[weak]
                obj,
                move |_| {
                    obj.update_notifications();
                }
            ));
            self.membership_handler.replace(Some(membership_handler));

            let permissions_handler = room.permissions().connect_changed(clone!(
                #[weak]
                obj,
                move |_| {
                    obj.update_upgrade_button();
                    obj.update_edit_addresses_button();
                    obj.update_join_rule();
                    obj.update_guest_access();
                    obj.update_history_visibility();
                    obj.update_encryption();

                    spawn!(async move {
                        obj.update_publish().await;
                    });
                }
            ));
            self.permissions_handler.replace(Some(permissions_handler));

            let aliases = room.aliases();
            let canonical_alias_handler = aliases.connect_canonical_alias_string_notify(clone!(
                #[weak]
                obj,
                move |_| {
                    obj.update_addresses();
                }
            ));
            self.canonical_alias_handler
                .replace(Some(canonical_alias_handler));

            let alt_aliases_handler = aliases.alt_aliases_model().connect_items_changed(clone!(
                #[weak]
                obj,
                move |_, _, _, _| {
                    obj.update_addresses();
                }
            ));
            self.alt_aliases_handler.replace(Some(alt_aliases_handler));

            let join_rule_handler = room.join_rule().connect_changed(clone!(
                #[weak]
                obj,
                move |_| {
                    obj.update_join_rule();
                }
            ));
            self.join_rule_handler.replace(Some(join_rule_handler));

            let room_handler_ids = vec![
                room.connect_joined_members_count_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_members();
                    }
                )),
                room.connect_is_direct_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_members();
                    }
                )),
                room.connect_category_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_members();
                    }
                )),
                room.connect_notifications_setting_notify(clone!(
                    #[weak]
                    obj,
                    move |_| {
                        obj.update_notifications();
                    }
                )),
                room.connect_is_tombstoned_notify(clone!(
                    #[weak]
                    obj,
                    move |_| {
                        obj.update_upgrade_button();
                    }
                )),
                room.connect_guests_allowed_notify(clone!(
                    #[weak]
                    obj,
                    move |_| {
                        obj.update_guest_access();
                    }
                )),
                room.connect_history_visibility_notify(clone!(
                    #[weak]
                    obj,
                    move |_| {
                        obj.update_history_visibility();
                    }
                )),
                room.connect_is_encrypted_notify(clone!(
                    #[weak]
                    obj,
                    move |_| {
                        obj.update_encryption();
                    }
                )),
            ];

            self.room.set(room, room_handler_ids);
            obj.notify_room();

            if let Some(session) = room.session() {
                let settings = session.notifications().settings();
                let notifications_settings_handlers = vec![
                    settings.connect_account_enabled_notify(clone!(
                        #[weak]
                        obj,
                        move |_| {
                            obj.update_notifications();
                        }
                    )),
                    settings.connect_session_enabled_notify(clone!(
                        #[weak]
                        obj,
                        move |_| {
                            obj.update_notifications();
                        }
                    )),
                ];

                self.notifications_settings_handlers
                    .replace(notifications_settings_handlers);
            }

            self.init_edit_details();
            self.update_members();
            obj.update_notifications();
            obj.update_edit_addresses_button();
            obj.update_addresses();
            obj.update_federated();
            obj.update_join_rule();
            obj.update_guest_access();
            obj.update_publish_title();
            obj.update_history_visibility();
            obj.update_encryption();
            obj.update_upgrade_button();

            spawn!(clone!(
                #[weak]
                obj,
                async move {
                    obj.update_publish().await;
                }
            ));

            self.load_capabilities();
        }

        /// Set the lists of members filtered by membership for the room.
        fn set_membership_lists(&self, membership_lists: &MembershipLists) {
            self.membership_lists.set(Some(membership_lists));
            self.update_members();
        }

        /// The notifications setting for the room.
        fn notifications_setting(&self) -> NotificationsRoomSetting {
            self.room
                .obj()
                .map(|r| r.notifications_setting())
                .unwrap_or_default()
        }

        /// Set the notifications setting for the room.
        fn set_notifications_setting(&self, setting: NotificationsRoomSetting) {
            if self.notifications_setting() == setting {
                return;
            }

            self.obj().notifications_setting_changed(setting);
        }

        /// Fetch the capabilities of the homeserver.
        fn load_capabilities(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };
            let client = room.matrix_room().client();

            spawn!(
                glib::Priority::LOW,
                clone!(
                    #[weak(rename_to = imp)]
                    self,
                    async move {
                        let handle = spawn_tokio!(async move { client.get_capabilities().await });
                        match handle.await.unwrap() {
                            Ok(capabilities) => {
                                imp.capabilities.replace(capabilities);
                            }
                            Err(error) => {
                                error!("Could not get server capabilities: {error}");
                                imp.capabilities.take();
                            }
                        }
                    }
                )
            );
        }

        /// Initialize the button to edit details.
        fn init_edit_details(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            // Hide edit button when the user cannot edit any detail or when the room is
            // direct.
            let permissions = room.permissions();
            let can_change_avatar = permissions.property_expression("can-change-avatar");
            let can_change_name = permissions.property_expression("can-change-name");
            let can_change_topic = permissions.property_expression("can-change-topic");

            let can_change_name_or_topic = expression::or(can_change_name, can_change_topic);
            let can_edit_at_least_one_detail =
                expression::or(can_change_name_or_topic, can_change_avatar);

            let is_direct_expr = room.property_expression("is-direct");

            let expr_watch = expression::and(
                expression::not(is_direct_expr),
                can_edit_at_least_one_detail,
            )
            .bind(&*self.edit_details_btn, "visible", gtk::Widget::NONE);
            self.expr_watch.replace(Some(expr_watch));
        }

        /// Update the members section.
        fn update_members(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };
            let Some(membership_lists) = self.membership_lists.upgrade() else {
                return;
            };

            let joined_members_count = membership_lists.joined().n_items();

            // When the room is direct there should only be 2 members in most cases, but use
            // the members count to make sure we do not show a list that is too long.
            let is_direct_with_few_members = room.is_direct() && joined_members_count < 5;
            if is_direct_with_few_members {
                let title = ngettext("Member", "Members", joined_members_count);
                self.direct_members_group.set_title(&title);

                // Set model of direct members list dynamically to avoid creating unnecessary
                // widgets in the background.
                if !self.direct_members_list_has_bound_model.get() {
                    self.direct_members_list
                        .bind_model(Some(&membership_lists.joined()), |item| {
                            let member = item
                                .downcast_ref::<Member>()
                                .expect("joined members list contains members");
                            let member_row = MemberRow::new(false);
                            member_row.set_member(Some(member));

                            gtk::ListBoxRow::builder()
                                .selectable(false)
                                .child(&member_row)
                                .action_name("details.show-member")
                                .action_target(&member.user_id().as_str().to_variant())
                                .build()
                                .upcast()
                        });
                    self.direct_members_list_has_bound_model.set(true);
                }

                let has_members = joined_members_count > 0;
                self.direct_members_list.set_visible(has_members);
                self.no_direct_members_label.set_visible(!has_members);
            } else {
                let mut server_joined_members_count = room.joined_members_count();

                if room.category() == RoomCategory::Left {
                    // The number of joined members count from the homeserver is only updated when
                    // we are joined, so we must at least remove ourself from the count after we
                    // left.
                    server_joined_members_count = server_joined_members_count.saturating_sub(1);
                }

                // Use the maximum between the count of joined members in the local list, and
                // the one provided by the homeserver. The homeserver is usually right, except
                // when we just joined a room, where it will be 0 for a while.
                let joined_members_count =
                    server_joined_members_count.max(joined_members_count.into());
                self.members_row.set_count(joined_members_count.to_string());

                let n = joined_members_count.try_into().unwrap_or(u32::MAX);
                let title = ngettext("Member", "Members", n);
                self.members_row.set_title(&title);

                if self.direct_members_list_has_bound_model.get() {
                    self.direct_members_list
                        .bind_model(None::<&gio::ListModel>, |_item| {
                            gtk::ListBoxRow::new().upcast()
                        });
                    self.direct_members_list_has_bound_model.set(false);
                }
            }

            self.direct_members_group
                .set_visible(is_direct_with_few_members);
            self.members_row_group
                .set_visible(!is_direct_with_few_members);
        }

        /// Disconnect all the signals.
        fn disconnect_all(&self) {
            if let Some(room) = self.room.obj() {
                if let Some(session) = room.session() {
                    let settings = session.notifications().settings();
                    for handler in self.notifications_settings_handlers.take() {
                        settings.disconnect(handler);
                    }
                }

                if let Some(handler) = self.membership_handler.take() {
                    room.own_member().disconnect(handler);
                }

                if let Some(handler) = self.permissions_handler.take() {
                    room.permissions().disconnect(handler);
                }

                let aliases = room.aliases();
                if let Some(handler) = self.canonical_alias_handler.take() {
                    aliases.disconnect(handler);
                }
                if let Some(handler) = self.alt_aliases_handler.take() {
                    aliases.alt_aliases_model().disconnect(handler);
                }

                if let Some(handler) = self.join_rule_handler.take() {
                    room.join_rule().disconnect(handler);
                }
            }

            self.room.disconnect_signals();

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

glib::wrapper! {
    /// Preference Window to display and update room details.
    pub struct GeneralPage(ObjectSubclass<imp::GeneralPage>)
        @extends gtk::Widget, adw::PreferencesPage, @implements gtk::Accessible;
}

#[gtk::template_callbacks]
impl GeneralPage {
    pub fn new(room: &Room, membership_lists: &MembershipLists) -> Self {
        glib::Object::builder()
            .property("room", room)
            .property("membership-lists", membership_lists)
            .build()
    }

    /// Unselect the topic of the room.
    ///
    /// This is to circumvent the default GTK behavior to select all the text
    /// when opening the details.
    pub fn unselect_topic(&self) {
        let imp = self.imp();

        glib::idle_add_local_once(clone!(
            #[weak]
            imp,
            move || {
                // Put the cursor at the beginning of the title instead of having the title
                // selected, if it is visible.
                if imp.room_topic.is_visible() {
                    imp.room_topic.select_region(0, 0);
                }
            }
        ));
    }

    /// Update the section about notifications.
    fn update_notifications(&self) {
        let Some(room) = self.room() else {
            return;
        };
        let imp = self.imp();

        if !room.is_joined() {
            imp.notifications.set_visible(false);
            return;
        }

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

        // Updates the active radio button.
        self.notify_notifications_setting();

        let settings = session.notifications().settings();
        let sensitive = settings.account_enabled()
            && settings.session_enabled()
            && !self.notifications_loading();
        imp.notifications.set_sensitive(sensitive);
        imp.notifications.set_visible(true);
    }

    /// Update the loading state in the notifications section.
    fn set_notifications_loading(&self, loading: bool, setting: NotificationsRoomSetting) {
        let imp = self.imp();

        // Only show the spinner on the selected one.
        imp.notifications_global_row
            .set_is_loading(loading && setting == NotificationsRoomSetting::Global);
        imp.notifications_all_row
            .set_is_loading(loading && setting == NotificationsRoomSetting::All);
        imp.notifications_mentions_row
            .set_is_loading(loading && setting == NotificationsRoomSetting::MentionsOnly);
        imp.notifications_mute_row
            .set_is_loading(loading && setting == NotificationsRoomSetting::Mute);

        self.imp().notifications_loading.set(loading);
        self.notify_notifications_loading();
    }

    /// Handle a change of the notifications setting.
    fn notifications_setting_changed(&self, setting: NotificationsRoomSetting) {
        let Some(room) = self.room() else {
            return;
        };
        let Some(session) = room.session() else {
            return;
        };
        let imp = self.imp();

        if setting == room.notifications_setting() {
            // Nothing to do.
            return;
        }

        imp.notifications.set_sensitive(false);
        self.set_notifications_loading(true, setting);

        let settings = session.notifications().settings();
        spawn!(clone!(
            #[weak(rename_to = obj)]
            self,
            async move {
                if settings
                    .set_per_room_setting(room.room_id().to_owned(), setting)
                    .await
                    .is_err()
                {
                    toast!(obj, gettext("Could not change notifications setting"));
                }

                obj.set_notifications_loading(false, setting);
                obj.update_notifications();
            }
        ));
    }

    /// Update the button to edit addresses.
    fn update_edit_addresses_button(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let can_edit = room.is_joined()
            && room
                .permissions()
                .is_allowed_to(PowerLevelAction::SendState(StateEventType::RoomPowerLevels));
        self.imp().edit_addresses_button.set_visible(can_edit);
    }

    /// Update the addresses group.
    fn update_addresses(&self) {
        let Some(room) = self.room() else {
            return;
        };
        let imp = self.imp();
        let aliases = room.aliases();

        let canonical_alias_string = aliases.canonical_alias_string();
        let has_canonical_alias = canonical_alias_string.is_some();

        if let Some(canonical_alias_string) = canonical_alias_string {
            let mut row_borrow = imp.canonical_alias_row.borrow_mut();
            let row = row_borrow.get_or_insert_with(|| {
                // We want the main alias always at the top but cannot add a row at the top so
                // we have to remove the other rows first.
                self.remove_alt_aliases_rows();

                let row = CopyableRow::new();
                row.set_copy_button_tooltip_text(Some(gettext("Copy address")));
                row.set_toast_text(Some(gettext("Address copied to clipboard")));

                // Mark the main alias with a tag.
                let label = gtk::Label::builder()
                    .label(gettext("Main Address"))
                    .ellipsize(pango::EllipsizeMode::End)
                    .css_classes(["public-address-tag"])
                    .valign(gtk::Align::Center)
                    .build();
                row.update_relation(&[gtk::accessible::Relation::DescribedBy(&[
                    label.upcast_ref()
                ])]);
                row.set_extra_suffix(Some(label));

                imp.addresses_group.add(&row);

                row
            });

            row.set_title(&canonical_alias_string);
        } else if let Some(row) = imp.canonical_alias_row.take() {
            imp.addresses_group.remove(&row);
        }

        let alt_aliases = aliases.alt_aliases_model();
        let alt_aliases_count = alt_aliases.n_items() as usize;
        if alt_aliases_count == 0 {
            self.remove_alt_aliases_rows();
        } else {
            let mut rows = imp.alt_aliases_rows.borrow_mut();

            for (pos, alt_alias) in alt_aliases.iter::<glib::Object>().enumerate() {
                let Some(alt_alias) = alt_alias.ok().and_downcast::<gtk::StringObject>() else {
                    break;
                };

                let row = rows.get(pos).cloned().unwrap_or_else(|| {
                    let row = CopyableRow::new();
                    row.set_copy_button_tooltip_text(Some(gettext("Copy address")));
                    row.set_toast_text(Some(gettext("Address copied to clipboard")));

                    imp.addresses_group.add(&row);
                    rows.push(row.clone());

                    row
                });

                row.set_title(&alt_alias.string());
            }

            let rows_count = rows.len();
            if alt_aliases_count < rows_count {
                for _ in alt_aliases_count..rows_count {
                    if let Some(row) = rows.pop() {
                        imp.addresses_group.remove(&row);
                    }
                }
            }
        }

        imp.no_addresses_label
            .set_visible(!has_canonical_alias && alt_aliases_count == 0);
    }

    fn remove_alt_aliases_rows(&self) {
        let imp = self.imp();

        for row in imp.alt_aliases_rows.take() {
            imp.addresses_group.remove(&row);
        }
    }

    /// Copy the room's permalink to the clipboard.
    #[template_callback]
    async fn copy_permalink(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let permalink = room.matrix_to_uri().await;
        self.clipboard().set_text(&permalink.to_string());
        toast!(self, gettext("Room link copied to clipboard"));
    }

    /// Update the join rule row.
    fn update_join_rule(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let row = &self.imp().join_rule;
        row.set_is_loading(false);

        let permissions = room.permissions();
        let join_rule = room.join_rule();

        let is_supported_join_rule = matches!(
            join_rule.value(),
            JoinRuleValue::Public | JoinRuleValue::Invite
        ) && !join_rule.can_knock();
        let can_change =
            permissions.is_allowed_to(PowerLevelAction::SendState(StateEventType::RoomJoinRules));

        row.set_read_only(!is_supported_join_rule || !can_change);
        row.set_selected_string(Some(join_rule.display_name()));
    }

    /// Set the join rule of the room.
    #[template_callback]
    async fn set_join_rule(&self) {
        let Some(room) = self.room() else {
            return;
        };
        let join_rule = room.join_rule();

        let row = &self.imp().join_rule;

        let value = match row.selected() {
            0 => JoinRuleValue::Invite,
            1 => JoinRuleValue::Public,
            _ => {
                return;
            }
        };

        if join_rule.value() == value {
            // Nothing to do.
            return;
        }

        row.set_is_loading(true);
        row.set_read_only(true);

        if join_rule.set_value(value).await.is_err() {
            toast!(self, gettext("Could not change who can join"));
            self.update_join_rule();
        }
    }

    /// Update the guest access row.
    fn update_guest_access(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let row = &self.imp().guest_access;
        row.set_is_active(room.guests_allowed());
        row.set_is_loading(false);

        let can_change = room
            .permissions()
            .is_allowed_to(PowerLevelAction::SendState(StateEventType::RoomGuestAccess));
        row.set_read_only(!can_change);
    }

    /// Toggle the guest access.
    #[template_callback]
    async fn toggle_guest_access(&self) {
        let Some(room) = self.room() else { return };

        let row = &self.imp().guest_access;
        let guests_allowed = row.is_active();

        if room.guests_allowed() == guests_allowed {
            return;
        }

        row.set_is_loading(true);
        row.set_read_only(true);

        let guest_access = if guests_allowed {
            GuestAccess::CanJoin
        } else {
            GuestAccess::Forbidden
        };
        let content = RoomGuestAccessEventContent::new(guest_access);

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

        if let Err(error) = handle.await.unwrap() {
            error!("Could not change guest access: {error}");
            toast!(self, gettext("Could not change guest access"));
            self.update_guest_access();
        }
    }

    /// Update the title of the publish row.
    fn update_publish_title(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let own_member = room.own_member();
        let server_name = own_member.user_id().server_name();

        let title = gettext_f(
            // Translators: Do NOT translate the content between '{' and '}',
            // this is a variable name.
            "Publish in the {homeserver} directory",
            &[("homeserver", server_name.as_str())],
        );
        self.imp().publish.set_title(&title);
    }

    /// Update the publish row.
    async fn update_publish(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let imp = self.imp();
        let row = &imp.publish;

        // There is no clear definition of who is allowed to publish a room to the
        // directory in the Matrix spec. Let's assume it doesn't make sense unless the
        // user can change the public addresses.
        let can_change = room
            .permissions()
            .is_allowed_to(PowerLevelAction::SendState(
                StateEventType::RoomCanonicalAlias,
            ));
        row.set_read_only(!can_change);

        let matrix_room = room.matrix_room();
        let client = matrix_room.client();
        let request = get_room_visibility::v3::Request::new(matrix_room.room_id().to_owned());

        let handle = spawn_tokio!(async move { client.send(request).await });

        match handle.await.unwrap() {
            Ok(response) => {
                let is_published = response.visibility == Visibility::Public;
                imp.is_published.set(is_published);
                row.set_is_active(is_published);
            }
            Err(error) => {
                error!("Could not get directory visibility of room: {error}");
            }
        }

        row.set_is_loading(false);
    }

    /// Toggle whether the room is published in the room directory.
    #[template_callback]
    async fn toggle_publish(&self) {
        let Some(room) = self.room() else { return };

        let imp = self.imp();
        let row = &imp.publish;
        let publish = row.is_active();

        if imp.is_published.get() == publish {
            return;
        }

        row.set_is_loading(true);
        row.set_read_only(true);

        let visibility = if publish {
            Visibility::Public
        } else {
            Visibility::Private
        };

        let matrix_room = room.matrix_room();
        let client = matrix_room.client();
        let request =
            set_room_visibility::v3::Request::new(matrix_room.room_id().to_owned(), visibility);

        let handle = spawn_tokio!(async move { client.send(request).await });

        if let Err(error) = handle.await.unwrap() {
            error!("Could not change directory visibility of room: {error}");
            let text = if publish {
                gettext("Could not publish room in directory")
            } else {
                gettext("Could not unpublish room from directory")
            };
            toast!(self, text);
        }

        self.update_publish().await;
    }

    /// Update the history visibility edit button.
    fn update_history_visibility(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let row = &self.imp().history_visibility;
        row.set_is_loading(false);

        let visibility = room.history_visibility();

        let text = match visibility {
            HistoryVisibilityValue::WorldReadable => {
                gettext("Anyone, even if they are not in the room")
            }
            HistoryVisibilityValue::Shared => {
                gettext("Members only, since this option was selected")
            }
            HistoryVisibilityValue::Invited => gettext("Members only, since they were invited"),
            HistoryVisibilityValue::Joined => gettext("Members only, since they joined the room"),
            HistoryVisibilityValue::Unsupported => gettext("Unsupported rule"),
        };
        row.set_selected_string(Some(text));

        let is_supported = visibility != HistoryVisibilityValue::Unsupported;
        let can_change = room
            .permissions()
            .is_allowed_to(PowerLevelAction::SendState(
                StateEventType::RoomHistoryVisibility,
            ));

        row.set_read_only(!is_supported || !can_change);
    }

    /// Set the history_visibility of the room.
    #[template_callback]
    async fn set_history_visibility(&self) {
        let Some(room) = self.room() else {
            return;
        };
        let row = &self.imp().history_visibility;

        let visibility = match row.selected() {
            0 => HistoryVisibilityValue::WorldReadable,
            1 => HistoryVisibilityValue::Shared,
            2 => HistoryVisibilityValue::Joined,
            3 => HistoryVisibilityValue::Invited,
            _ => {
                return;
            }
        };

        if room.history_visibility() == visibility {
            // Nothing to do.
            return;
        }

        row.set_is_loading(true);
        row.set_read_only(true);

        let content = RoomHistoryVisibilityEventContent::new(visibility.into());

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

        if let Err(error) = handle.await.unwrap() {
            error!("Could not change room history visibility: {error}");
            toast!(self, gettext("Could not change who can read history"));

            self.update_history_visibility();
        }
    }

    /// Update the encryption row.
    fn update_encryption(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let imp = self.imp();
        let row = &imp.encryption;
        row.set_is_loading(false);

        let is_encrypted = room.is_encrypted();
        row.set_is_active(is_encrypted);

        let can_change = !is_encrypted
            && room
                .permissions()
                .is_allowed_to(PowerLevelAction::SendState(StateEventType::RoomEncryption));
        row.set_read_only(!can_change);
    }

    /// Enable encryption in the room.
    #[template_callback]
    async fn enable_encryption(&self) {
        let Some(room) = self.room() else { return };

        let imp = self.imp();
        let row = &imp.encryption;

        if room.is_encrypted() || !row.is_active() {
            // Nothing to do.
            return;
        }

        row.set_is_loading(true);
        row.set_read_only(true);

        // Ask for confirmation.
        let dialog = adw::AlertDialog::builder()
                .heading(gettext("Enable Encryption?"))
                .body(gettext("Enabling encryption will prevent new members to read the history before they arrived. This cannot be disabled later."))
                .default_response("cancel")
                .build();
        dialog.add_responses(&[
            ("cancel", &gettext("Cancel")),
            ("enable", &gettext("Enable")),
        ]);
        dialog.set_response_appearance("enable", adw::ResponseAppearance::Destructive);

        if dialog.choose_future(self).await != "enable" {
            self.update_encryption();
            return;
        };

        if room.enable_encryption().await.is_err() {
            toast!(self, gettext("Could not enable encryption"));
            self.update_encryption();
        }
    }

    /// Update the room upgrade button.
    fn update_upgrade_button(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let can_upgrade = !room.is_tombstoned()
            && room
                .permissions()
                .is_allowed_to(PowerLevelAction::SendState(StateEventType::RoomTombstone));
        self.imp().upgrade_button.set_visible(can_upgrade);
    }

    /// Update the room federation row.
    fn update_federated(&self) {
        let Some(room) = self.room() else {
            return;
        };

        let subtitle = if room.federated() {
            // Translators: As in, 'Room federated'.
            gettext("Federated")
        } else {
            // Translators: As in, 'Room not federated'.
            gettext("Not federated")
        };

        self.imp().room_federated.set_subtitle(&subtitle);
    }

    /// Upgrade the room to a new version.
    #[template_callback]
    async fn upgrade(&self) {
        let Some(room) = self.room() else {
            return;
        };
        let imp = self.imp();

        // TODO: Hide upgrade button if room already upgraded?
        imp.upgrade_button.set_is_loading(true);
        let room_versions_capability = imp.capabilities.borrow().room_versions.clone();

        let Some(new_version) = confirm_room_upgrade(room_versions_capability, self).await else {
            imp.upgrade_button.set_is_loading(false);
            return;
        };

        let client = room.matrix_room().client();
        let request = upgrade_room::v3::Request::new(room.room_id().to_owned(), new_version);

        let handle = spawn_tokio!(async move { client.send(request).await });

        match handle.await.unwrap() {
            Ok(_) => {
                toast!(self, gettext("Room upgraded successfully"));
            }
            Err(error) => {
                error!("Could not upgrade room: {error}");
                toast!(self, gettext("Could not upgrade room"));
                imp.upgrade_button.set_is_loading(false);
            }
        }
    }
}