fractal/session/view/content/room_history/
mod.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
mod divider_row;
mod item_row;
mod member_timestamp;
mod message_row;
mod message_toolbar;
mod read_receipts_list;
mod sender_avatar;
mod state_row;
mod title;
mod typing_row;
mod verification_info_bar;

use std::time::Duration;

use adw::{prelude::*, subclass::prelude::*};
use gettextrs::gettext;
use gtk::{gdk, gio, glib, glib::clone, graphene::Point, CompositeTemplate};
use matrix_sdk::ruma::EventId;
use ruma::{api::client::receipt::create_receipt::v3::ReceiptType, OwnedEventId};
use tracing::{error, warn};

use self::{
    divider_row::DividerRow, item_row::ItemRow, message_row::MessageRow,
    message_toolbar::MessageToolbar, read_receipts_list::ReadReceiptsList,
    sender_avatar::SenderAvatar, state_row::StateRow, title::RoomHistoryTitle,
    typing_row::TypingRow, verification_info_bar::VerificationInfoBar,
};
use super::{room_details, RoomDetails};
use crate::{
    components::{confirm_leave_room_dialog, DragOverlay, ReactionChooser},
    prelude::*,
    session::model::{
        Event, EventKey, MemberList, Membership, ReceiptPosition, Room, RoomCategory, Timeline,
        TimelineState,
    },
    spawn, toast,
    utils::{template_callbacks::TemplateCallbacks, BoundObject},
    Window,
};

/// The time to wait before considering that scrolling has ended.
const SCROLL_TIMEOUT: Duration = Duration::from_millis(500);
/// The time to wait before considering that messages on a screen where read.
const READ_TIMEOUT: Duration = Duration::from_secs(5);

mod imp {
    use std::{
        cell::{Cell, OnceCell, RefCell},
        marker::PhantomData,
        ops::ControlFlow,
    };

    use glib::subclass::InitializingObject;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(resource = "/org/gnome/Fractal/ui/session/view/content/room_history/mod.ui")]
    #[properties(wrapper_type = super::RoomHistory)]
    pub struct RoomHistory {
        #[template_child]
        pub(super) sender_menu_model: TemplateChild<gio::Menu>,
        #[template_child]
        pub(super) header_bar: TemplateChild<adw::HeaderBar>,
        #[template_child]
        room_menu: TemplateChild<gtk::MenuButton>,
        #[template_child]
        listview: TemplateChild<gtk::ListView>,
        #[template_child]
        content: TemplateChild<gtk::Widget>,
        #[template_child]
        scrolled_window: TemplateChild<gtk::ScrolledWindow>,
        #[template_child]
        scroll_btn: TemplateChild<gtk::Button>,
        #[template_child]
        scroll_btn_revealer: TemplateChild<gtk::Revealer>,
        #[template_child]
        pub(super) message_toolbar: TemplateChild<MessageToolbar>,
        #[template_child]
        loading: TemplateChild<adw::Spinner>,
        #[template_child]
        error: TemplateChild<adw::StatusPage>,
        #[template_child]
        stack: TemplateChild<gtk::Stack>,
        #[template_child]
        tombstoned_banner: TemplateChild<adw::Banner>,
        #[template_child]
        drag_overlay: TemplateChild<DragOverlay>,
        pub(super) item_context_menu: OnceCell<gtk::PopoverMenu>,
        pub(super) item_reaction_chooser: ReactionChooser,
        pub(super) sender_context_menu: OnceCell<gtk::PopoverMenu>,
        /// The room currently displayed.
        #[property(get, set = Self::set_room, explicit_notify, nullable)]
        room: BoundObject<Room>,
        /// Whether this is the only view visible, i.e. there is no sidebar.
        #[property(get, set)]
        is_only_view: Cell<bool>,
        /// Whether this `RoomHistory` is empty, aka no room is currently
        /// displayed.
        #[property(get = Self::is_empty)]
        is_empty: PhantomData<bool>,
        /// The members of the current room.
        ///
        /// We hold a strong reference here to keep the list in memory as long
        /// as the room is opened.
        pub(super) room_members: RefCell<Option<MemberList>>,
        timeline_handlers: RefCell<Vec<glib::SignalHandlerId>>,
        /// Whether the current room history scrolling is automatic.
        is_auto_scrolling: Cell<bool>,
        /// Whether the room history should stick to the newest message in the
        /// timeline.
        #[property(get, explicit_notify)]
        is_sticky: Cell<bool>,
        /// The `GtkSelectionModel` used in the list view.
        selection_model: OnceCell<gtk::NoSelection>,
        scroll_timeout: RefCell<Option<glib::SourceId>>,
        read_timeout: RefCell<Option<glib::SourceId>>,
        can_invite_handler: RefCell<Option<glib::SignalHandlerId>>,
        membership_handler: RefCell<Option<glib::SignalHandlerId>>,
        join_rule_handler: RefCell<Option<glib::SignalHandlerId>>,
    }

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

        fn class_init(klass: &mut Self::Class) {
            RoomHistoryTitle::ensure_type();
            ItemRow::ensure_type();
            VerificationInfoBar::ensure_type();
            Timeline::ensure_type();

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

            klass.set_accessible_role(gtk::AccessibleRole::Group);

            klass.install_action_async("room-history.leave", None, |obj, _, _| async move {
                obj.imp().leave().await;
            });
            klass.install_action_async("room-history.join", None, |obj, _, _| async move {
                obj.imp().join().await;
            });
            klass.install_action_async("room-history.forget", None, |obj, _, _| async move {
                obj.imp().forget().await;
            });

            klass.install_action("room-history.details", None, |obj, _, _| {
                obj.open_room_details(None);
            });
            klass.install_action("room-history.invite-members", None, |obj, _, _| {
                obj.open_room_details(Some(room_details::SubpageName::Invite));
            });

            klass.install_action(
                "room-history.scroll-to-event",
                Some(&EventKey::static_variant_type()),
                |obj, _, v| {
                    if let Some(event_key) = v.and_then(EventKey::from_variant) {
                        obj.imp().scroll_to_event(&event_key);
                    }
                },
            );

            klass.install_action(
                "room-history.reply",
                Some(&String::static_variant_type()),
                |obj, _, v| {
                    if let Some(event_id) = v
                        .and_then(String::from_variant)
                        .and_then(|s| EventId::parse(s).ok())
                    {
                        if let Some(event) = obj
                            .room()
                            .and_then(|room| {
                                room.timeline().event_by_key(&EventKey::EventId(event_id))
                            })
                            .and_downcast_ref()
                        {
                            obj.message_toolbar().set_reply_to(event);
                        }
                    }
                },
            );

            klass.install_action(
                "room-history.edit",
                Some(&String::static_variant_type()),
                |obj, _, v| {
                    if let Some(event_id) = v
                        .and_then(String::from_variant)
                        .and_then(|s| EventId::parse(s).ok())
                    {
                        if let Some(event) = obj
                            .room()
                            .and_then(|room| {
                                room.timeline().event_by_key(&EventKey::EventId(event_id))
                            })
                            .and_downcast_ref()
                        {
                            obj.message_toolbar().set_edit(event);
                        }
                    }
                },
            );
        }

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

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

            self.init_listview();
            self.init_drop_target();

            self.scroll_btn_revealer
                .connect_child_revealed_notify(|revealer| {
                    // Hide the revealer when we don't want to show the child and the animation is
                    // finished.
                    if !revealer.reveals_child() && !revealer.is_child_revealed() {
                        revealer.set_visible(false);
                    }
                });
        }

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

    impl WidgetImpl for RoomHistory {}
    impl BinImpl for RoomHistory {}

    impl RoomHistory {
        /// Initialize the list view.
        fn init_listview(&self) {
            let obj = self.obj();

            let factory = gtk::SignalListItemFactory::new();
            factory.connect_setup(clone!(
                #[weak]
                obj,
                move |_, item| {
                    let Some(item) = item.downcast_ref::<gtk::ListItem>() else {
                        error!("List item factory did not receive a list item: {item:?}");
                        return;
                    };
                    let row = ItemRow::new(&obj);
                    item.set_child(Some(&row));
                    item.bind_property("item", &row, "item").build();
                    item.set_activatable(false);
                    item.set_selectable(false);
                }
            ));
            self.listview.set_factory(Some(&factory));

            // Needed to use the natural height of GtkPictures
            self.listview
                .set_vscroll_policy(gtk::ScrollablePolicy::Natural);

            self.listview.set_model(Some(self.selection_model()));

            self.set_sticky(true);
            let adj = self.listview.vadjustment().unwrap();

            adj.connect_value_changed(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    tracing::trace!("Scroll value changed");
                    imp.trigger_read_receipts_update();

                    let is_at_bottom = imp.is_at_bottom();
                    if imp.is_auto_scrolling.get() {
                        tracing::trace!("Automatically scrolled");
                        if is_at_bottom {
                            imp.set_is_auto_scrolling(false);
                            imp.set_sticky(true);
                        } else {
                            imp.scroll_down();
                        }
                    } else {
                        tracing::trace!("User scrolled");
                        imp.set_sticky(is_at_bottom);
                    }

                    // Remove the typing row if we scroll up.
                    if !is_at_bottom {
                        if let Some(room) = imp.room.obj() {
                            room.timeline().remove_empty_typing_row();
                        }
                    }

                    imp.load_more_events_if_needed();
                }
            ));
            adj.connect_upper_notify(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    tracing::trace!("Scroll upper changed");
                    if imp.is_sticky.get() {
                        imp.scroll_down();
                    }
                    imp.load_more_events_if_needed();
                }
            ));
            adj.connect_page_size_notify(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    tracing::trace!("Scroll page size changed");
                    if imp.is_sticky.get() {
                        imp.scroll_down();
                    }
                    imp.load_more_events_if_needed();
                }
            ));
        }

        /// Whether the list view is scrolled at the bottom.
        pub(super) fn is_at_bottom(&self) -> bool {
            let adj = self
                .listview
                .vadjustment()
                .expect("GtkListView has a vadjustment");
            (adj.value() + adj.page_size() - adj.upper()).abs() < 0.0001
        }

        /// Initialize the drop target.
        fn init_drop_target(&self) {
            let target = gtk::DropTarget::new(
                gio::File::static_type(),
                gdk::DragAction::COPY | gdk::DragAction::MOVE,
            );

            target.connect_drop(clone!(
                #[weak(rename_to = imp)]
                self,
                #[upgrade_or]
                false,
                move |_, value, _, _| {
                    match value.get::<gio::File>() {
                        Ok(file) => {
                            spawn!(async move {
                                imp.message_toolbar.send_file(file).await;
                            });
                            true
                        }
                        Err(error) => {
                            warn!("Could not get file from drop: {error:?}");
                            toast!(imp.obj(), gettext("Error getting file from drop"));

                            false
                        }
                    }
                }
            ));

            self.drag_overlay.set_drop_target(target);
        }

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

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

            self.room.disconnect_signals();
        }

        /// Set the room currently displayed.
        #[allow(clippy::too_many_lines)]
        fn set_room(&self, room: Option<Room>) {
            if self.room.obj() == room {
                return;
            }

            self.disconnect_all();
            if let Some(source_id) = self.scroll_timeout.take() {
                source_id.remove();
            }
            if let Some(source_id) = self.read_timeout.take() {
                source_id.remove();
            }

            if let Some(room) = room {
                let timeline = room.timeline();

                // Keep a strong reference to the members list before changing the model, so all
                // events use the same list.
                self.room_members
                    .replace(Some(room.get_or_create_members()));

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

                let join_rule_handler = room.join_rule().connect_we_can_join_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_room_menu();
                    }
                ));
                self.join_rule_handler.replace(Some(join_rule_handler));

                let can_invite_handler = room.permissions().connect_can_invite_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_invite_action();
                    }
                ));
                self.can_invite_handler.replace(Some(can_invite_handler));

                let is_direct_handler = room.connect_is_direct_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_invite_action();
                    }
                ));
                let tombstoned_handler = room.connect_is_tombstoned_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_tombstoned_banner();
                    }
                ));
                let successor_id_handler = room.connect_successor_id_string_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_tombstoned_banner();
                    }
                ));
                let successor_handler = room.connect_successor_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_tombstoned_banner();
                    }
                ));

                self.room.set(
                    room,
                    vec![
                        is_direct_handler,
                        tombstoned_handler,
                        successor_id_handler,
                        successor_handler,
                    ],
                );

                let empty_handler = timeline.connect_is_empty_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_view();
                    }
                ));

                let state_handler = timeline.connect_state_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |timeline| {
                        imp.update_view();

                        // Always test if we need to load more when the timeline is ready.
                        // This is mostly to make sure that we load events if the timeline was not
                        // initialized when the room was opened.
                        if timeline.state() == TimelineState::Ready {
                            imp.load_more_events_if_needed();
                        }
                    }
                ));

                self.timeline_handlers
                    .replace(vec![empty_handler, state_handler]);

                timeline.remove_empty_typing_row();
                self.selection_model().set_model(Some(&timeline.items()));

                self.trigger_read_receipts_update();
                self.scroll_down();
            } else {
                self.selection_model().set_model(None::<&gio::ListModel>);
            }

            self.update_view();
            self.load_more_events_if_needed();
            self.update_room_menu();
            self.update_tombstoned_banner();
            self.update_invite_action();

            let obj = self.obj();
            obj.notify_room();
            obj.notify_is_empty();
        }

        /// The `GtkSelectionModel` used in the list view.
        fn selection_model(&self) -> &gtk::NoSelection {
            self.selection_model
                .get_or_init(|| gtk::NoSelection::new(gio::ListModel::NONE.cloned()))
        }

        /// Whether this `RoomHistory` is empty, aka no room is currently
        /// displayed.
        fn is_empty(&self) -> bool {
            self.room.obj().is_none()
        }

        /// Set whether the room history should stick to the newest message in
        /// the timeline.
        pub(super) fn set_sticky(&self, is_sticky: bool) {
            tracing::trace!("set_sticky: {is_sticky:?}");
            if self.is_sticky.get() == is_sticky {
                return;
            }
            tracing::trace!("is-sticky changed");

            if !is_sticky {
                self.scroll_btn_revealer.set_visible(true);
            }
            self.scroll_btn_revealer.set_reveal_child(!is_sticky);

            self.is_sticky.set(is_sticky);
            self.obj().notify_is_sticky();
        }

        /// Set whether the current room history scrolling is automatic.
        pub(super) fn set_is_auto_scrolling(&self, is_auto: bool) {
            tracing::trace!("set_is_auto_scrolling: {is_auto:?}");
            if self.is_auto_scrolling.get() == is_auto {
                return;
            }

            tracing::trace!("is_auto_scrolling changed");
            self.is_auto_scrolling.set(is_auto);
        }

        /// Scroll to the bottom of the timeline.
        pub(super) fn scroll_down(&self) {
            tracing::trace!("scroll_down");
            self.set_is_auto_scrolling(true);

            let n_items = self.selection_model().n_items();

            if n_items > 0 {
                // Make sure that the last item is focused.
                self.listview
                    .scroll_to(n_items - 1, gtk::ListScrollFlags::FOCUS, None);
                // Make sure that we do scroll to the very bottom.
                self.scrolled_window
                    .emit_scroll_child(gtk::ScrollType::End, false);
            }
        }

        /// Update the room menu for the current state.
        fn update_room_menu(&self) {
            let Some(room) = self.room.obj() else {
                self.room_menu.set_visible(false);
                return;
            };

            let obj = self.obj();
            let membership = room.own_member().membership();
            obj.action_set_enabled("room-history.leave", membership == Membership::Join);
            obj.action_set_enabled(
                "room-history.join",
                membership == Membership::Leave && room.join_rule().we_can_join(),
            );
            obj.action_set_enabled(
                "room-history.forget",
                matches!(membership, Membership::Leave | Membership::Ban),
            );

            self.room_menu.set_visible(true);
        }

        /// Update the view for the current state.
        fn update_view(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            let visible_child_name = if room.timeline().is_empty() {
                if room.timeline().state() == TimelineState::Error {
                    "error"
                } else {
                    "loading"
                }
            } else {
                "content"
            };
            self.stack.set_visible_child_name(visible_child_name);
        }

        /// Whether we need to load more events.
        fn needs_more_events(&self) -> bool {
            if self.selection_model().n_items() == 0 {
                // We definitely want events if the history is empty.
                return true;
            };

            // Load more messages when the user gets close to the top of the known room
            // history. Use the page size twice to detect if the user gets close to
            // the top.
            let adj = self
                .listview
                .vadjustment()
                .expect("GtkListView has a vadjustment");
            adj.value() < adj.page_size() * 2.0
        }

        /// Load more events at the beginning of the history if needed.
        fn load_more_events_if_needed(&self) {
            if !self.needs_more_events() {
                return;
            }

            self.load_more_events();
        }

        /// Load more events at the beginning of the history.
        pub(super) fn load_more_events(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            spawn!(clone!(
                #[weak(rename_to = imp)]
                self,
                async move {
                    room.timeline()
                        .load(clone!(
                            #[weak]
                            imp,
                            #[upgrade_or]
                            ControlFlow::Break(()),
                            move || {
                                if imp.needs_more_events() {
                                    ControlFlow::Continue(())
                                } else {
                                    ControlFlow::Break(())
                                }
                            }
                        ))
                        .await;
                }
            ));
        }

        /// Scroll to the event with the given key.
        fn scroll_to_event(&self, key: &EventKey) {
            let Some(room) = self.room.obj() else {
                return;
            };

            if let Some(pos) = room.timeline().find_event_position(key) {
                let pos = pos as u32;
                self.listview
                    .scroll_to(pos, gtk::ListScrollFlags::FOCUS, None);
            }
        }

        /// Trigger the process to update read receipts.
        fn trigger_read_receipts_update(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            let timeline = room.timeline();
            if !timeline.is_empty() {
                if let Some(source_id) = self.scroll_timeout.take() {
                    source_id.remove();
                }
                if let Some(source_id) = self.read_timeout.take() {
                    source_id.remove();
                }

                // Only send read receipt when scrolling stopped.
                self.scroll_timeout
                    .replace(Some(glib::timeout_add_local_once(
                        SCROLL_TIMEOUT,
                        clone!(
                            #[weak(rename_to = imp)]
                            self,
                            move || {
                                imp.update_read_receipts();
                            }
                        ),
                    )));
            }
        }

        /// Update the read receipts.
        fn update_read_receipts(&self) {
            self.scroll_timeout.take();

            if let Some(source_id) = self.read_timeout.take() {
                source_id.remove();
            }

            self.read_timeout.replace(Some(glib::timeout_add_local_once(
                READ_TIMEOUT,
                clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move || {
                        imp.update_read_marker();
                    }
                ),
            )));

            let Some(position) = self.receipt_position() else {
                return;
            };

            spawn!(clone!(
                #[weak(rename_to = imp)]
                self,
                async move {
                    let Some(room) = imp.room.obj() else { return };
                    room.send_receipt(ReceiptType::Read, position).await;
                }
            ));
        }

        /// Update the read marker.
        fn update_read_marker(&self) {
            self.read_timeout.take();

            let Some(position) = self.receipt_position() else {
                return;
            };

            spawn!(clone!(
                #[weak(rename_to = imp)]
                self,
                async move {
                    let Some(room) = imp.room.obj() else { return };
                    room.send_receipt(ReceiptType::FullyRead, position).await;
                }
            ));
        }

        /// The position where a receipt should point to.
        fn receipt_position(&self) -> Option<ReceiptPosition> {
            let position = if self.is_at_bottom() {
                ReceiptPosition::End
            } else {
                ReceiptPosition::Event(self.last_visible_event_id()?)
            };

            Some(position)
        }

        /// Get the ID of the last visible event in the room history.
        fn last_visible_event_id(&self) -> Option<OwnedEventId> {
            let listview = &*self.listview;
            let mut child = listview.last_child();
            // The visible part of the listview spans between 0 and max.
            let max = listview.height() as f32;

            while let Some(item) = child {
                // Vertical position of the top of the item.
                let top_pos = item
                    .compute_point(listview, &Point::new(0.0, 0.0))
                    .unwrap()
                    .y();
                // Vertical position of the bottom of the item.
                let bottom_pos = item
                    .compute_point(listview, &Point::new(0.0, item.height() as f32))
                    .unwrap()
                    .y();

                let top_in_view = top_pos > 0.0 && top_pos <= max;
                let bottom_in_view = bottom_pos > 0.0 && bottom_pos <= max;
                // If a message is too big and takes more space than the current view.
                let content_in_view = top_pos <= max && bottom_pos > 0.0;
                if top_in_view || bottom_in_view || content_in_view {
                    if let Some(event_id) = item
                        .first_child()
                        .and_downcast::<ItemRow>()
                        .and_then(|row| row.item())
                        .and_downcast::<Event>()
                        .and_then(|event| event.event_id())
                    {
                        return Some(event_id);
                    }
                }

                child = item.prev_sibling();
            }

            None
        }

        /// Update the tombstoned banner according to the state of the current
        /// room.
        fn update_tombstoned_banner(&self) {
            let banner = &self.tombstoned_banner;

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

            if !room.is_tombstoned() {
                banner.set_revealed(false);
                return;
            }

            if room.successor().is_some() {
                banner.set_title(&gettext("There is a newer version of this room"));
                // Translators: This is a verb, as in 'View Room'.
                banner.set_button_label(Some(&gettext("View")));
            } else if room.successor_id().is_some() {
                banner.set_title(&gettext("There is a newer version of this room"));
                banner.set_button_label(Some(&gettext("Join")));
            } else {
                banner.set_title(&gettext("This room was closed"));
                banner.set_button_label(None);
            }

            banner.set_revealed(true);
        }

        /// Leave the room.
        async fn leave(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            if confirm_leave_room_dialog(&room, &*self.obj())
                .await
                .is_none()
            {
                return;
            }

            if room.set_category(RoomCategory::Left).await.is_err() {
                toast!(
                    self.obj(),
                    gettext(
                        // Translators: Do NOT translate the content between '{' and '}', this is a variable name.
                        "Could not leave {room}",
                    ),
                    @room,
                );
            }
        }

        /// Join the room.
        async fn join(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            if room.set_category(RoomCategory::Normal).await.is_err() {
                toast!(
                    self.obj(),
                    gettext(
                        // Translators: Do NOT translate the content between '{' and '}', this is a
                        // variable name.
                        "Could not join {room}",
                    ),
                    @room,
                );
            }
        }

        /// Forget the room.
        async fn forget(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            if room.forget().await.is_err() {
                toast!(
                    self.obj(),
                    // Translators: Do NOT translate the content between '{' and '}', this is a variable name.
                    gettext("Could not forget {room}"),
                    @room,
                );
            }
        }

        // Update the invite action according to the current state.
        fn update_invite_action(&self) {
            let Some(room) = self.room.obj() else {
                return;
            };

            // Enable the invite action when we can invite but it is not a direct room.
            let can_invite = !room.is_direct() && room.permissions().can_invite();

            self.obj()
                .action_set_enabled("room-history.invite-members", can_invite);
        }
    }
}

glib::wrapper! {
    /// A view that displays the timeline of a room and ways to send new messages.
    pub struct RoomHistory(ObjectSubclass<imp::RoomHistory>)
        @extends gtk::Widget, adw::Bin, @implements gtk::Accessible;
}

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

    /// The header bar of the room history.
    pub fn header_bar(&self) -> &adw::HeaderBar {
        &self.imp().header_bar
    }

    /// The message toolbar of the room history.
    fn message_toolbar(&self) -> &MessageToolbar {
        &self.imp().message_toolbar
    }

    /// The members of the room currently displayed.
    pub fn room_members(&self) -> Option<MemberList> {
        self.imp().room_members.borrow().clone()
    }

    /// Opens the room details.
    ///
    /// If `subpage_name` is set, the room details will be opened on the given
    /// subpage.
    pub fn open_room_details(&self, subpage_name: Option<room_details::SubpageName>) {
        let Some(room) = self.room() else {
            return;
        };

        let window = RoomDetails::new(self.root().and_downcast_ref(), &room);
        if let Some(subpage_name) = subpage_name {
            window.show_initial_subpage(subpage_name);
        }
        window.present();
    }

    /// Load more events at the beginning of the history.
    #[template_callback]
    fn load_more_events(&self) {
        self.imp().load_more_events();
    }

    /// Scroll to the bottom of the timeline.
    #[template_callback]
    fn scroll_down(&self) {
        self.imp().scroll_down();
    }

    /// Enable or disable the mode allowing the room history to stick to the
    /// bottom based on scrollbar position.
    pub fn enable_sticky_mode(&self, enable: bool) {
        let imp = self.imp();
        if enable {
            imp.set_sticky(imp.is_at_bottom());
        } else {
            imp.set_sticky(false);
        }
    }

    /// Handle a paste action.
    pub fn handle_paste_action(&self) {
        self.message_toolbar().handle_paste_action();
    }

    /// The context menu for the item rows.
    pub fn item_context_menu(&self) -> &gtk::PopoverMenu {
        self.imp().item_context_menu.get_or_init(|| {
            let popover = gtk::PopoverMenu::builder()
                .has_arrow(false)
                .halign(gtk::Align::Start)
                .build();
            popover.update_property(&[gtk::accessible::Property::Label(&gettext("Context Menu"))]);
            popover
        })
    }

    /// The reaction chooser for the item rows.
    pub fn item_reaction_chooser(&self) -> &ReactionChooser {
        &self.imp().item_reaction_chooser
    }

    /// The context menu for the sender avatars.
    pub fn sender_context_menu(&self) -> &gtk::PopoverMenu {
        let imp = self.imp();
        imp.sender_context_menu.get_or_init(|| {
            let popover = gtk::PopoverMenu::builder()
                .has_arrow(false)
                .halign(gtk::Align::Start)
                .menu_model(&*imp.sender_menu_model)
                .build();
            popover.update_property(&[gtk::accessible::Property::Label(&gettext(
                "Sender Context Menu",
            ))]);
            popover
        })
    }

    /// Join or view the room's successor, if possible.
    #[template_callback]
    async fn join_or_view_successor(&self) {
        let Some(room) = self.room() else {
            return;
        };
        let Some(session) = room.session() else {
            return;
        };

        if !room.is_joined() || !room.is_tombstoned() {
            return;
        }

        if let Some(successor) = room.successor() {
            let Some(window) = self.root().and_downcast::<Window>() else {
                return;
            };

            window.show_room(session.session_id(), successor.room_id());
        } else if let Some(successor_id) = room.successor_id().map(ToOwned::to_owned) {
            let via = successor_id
                .server_name()
                .map(ToOwned::to_owned)
                .into_iter()
                .collect();

            if let Err(error) = session
                .room_list()
                .join_by_id_or_alias(successor_id.into(), via)
                .await
            {
                toast!(self, error);
            }
        }
    }
}