fractal/session/view/content/room_details/history_viewer/
audio.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
use adw::{prelude::*, subclass::prelude::*};
use gtk::{glib, glib::clone, CompositeTemplate};
use tracing::error;

use super::{AudioRow, HistoryViewerEvent, HistoryViewerEventType, HistoryViewerTimeline};
use crate::{
    components::LoadingRow, session::model::TimelineState, spawn, utils::BoundConstructOnlyObject,
};

/// The minimum number of items that should be loaded.
const MIN_N_ITEMS: u32 = 20;

mod imp {
    use std::ops::ControlFlow;

    use glib::subclass::InitializingObject;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(
        resource = "/org/gnome/Fractal/ui/session/view/content/room_details/history_viewer/audio.ui"
    )]
    #[properties(wrapper_type = super::AudioHistoryViewer)]
    pub struct AudioHistoryViewer {
        /// The timeline containing the audio events.
        #[property(get, set = Self::set_timeline, construct_only)]
        pub timeline: BoundConstructOnlyObject<HistoryViewerTimeline>,
        #[template_child]
        pub stack: TemplateChild<gtk::Stack>,
        #[template_child]
        pub list_view: TemplateChild<gtk::ListView>,
    }

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

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

            klass.set_css_name("audio-history-viewer");
        }

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

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

            let factory = gtk::SignalListItemFactory::new();

            factory.connect_bind(move |_, list_item| {
                let Some(list_item) = list_item.downcast_ref::<gtk::ListItem>() else {
                    error!("List item factory did not receive a list item: {list_item:?}");
                    return;
                };

                list_item.set_activatable(false);
                list_item.set_selectable(false);
            });
            factory.connect_bind(move |_, list_item| {
                let Some(list_item) = list_item.downcast_ref::<gtk::ListItem>() else {
                    error!("List item factory did not receive a list item: {list_item:?}");
                    return;
                };

                let item = list_item.item();

                if let Some(loading_row) = item
                    .and_downcast_ref::<LoadingRow>()
                    .filter(|_| !list_item.child().is_some_and(|c| c.is::<LoadingRow>()))
                {
                    loading_row.unparent();
                    loading_row.set_width_request(-1);
                    loading_row.set_height_request(-1);

                    list_item.set_child(Some(loading_row));
                } else if let Some(event) = item.and_downcast::<HistoryViewerEvent>() {
                    let audio_row =
                        if let Some(audio_row) = list_item.child().and_downcast::<AudioRow>() {
                            audio_row
                        } else {
                            let audio_row = AudioRow::new();
                            list_item.set_child(Some(&audio_row));

                            audio_row
                        };

                    audio_row.set_event(Some(event));
                }
            });

            self.list_view.set_factory(Some(&factory));
        }
    }

    impl WidgetImpl for AudioHistoryViewer {}
    impl NavigationPageImpl for AudioHistoryViewer {}

    impl AudioHistoryViewer {
        /// Set the timeline containing the audio events.
        fn set_timeline(&self, timeline: HistoryViewerTimeline) {
            let filter = gtk::CustomFilter::new(|obj| {
                obj.downcast_ref::<HistoryViewerEvent>()
                    .is_some_and(|e| e.event_type() == HistoryViewerEventType::Audio)
                    || obj.is::<LoadingRow>()
            });
            let filter_model =
                gtk::FilterListModel::new(Some(timeline.with_loading_item().clone()), Some(filter));

            let model = gtk::NoSelection::new(Some(filter_model));
            model.connect_items_changed(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_, _, _, _| {
                    imp.update_state();
                }
            ));
            self.list_view.set_model(Some(&model));

            let timeline_state_handler = timeline.connect_state_notify(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    imp.update_state();
                }
            ));

            self.timeline.set(timeline, vec![timeline_state_handler]);
            self.update_state();

            spawn!(clone!(
                #[weak(rename_to = imp)]
                self,
                async move {
                    imp.init_timeline().await;
                }
            ));
        }

        /// Initialize the timeline.
        async fn init_timeline(&self) {
            // Load an initial number of items.
            self.load_more_items().await;

            let adj = self
                .list_view
                .vadjustment()
                .expect("GtkListView has a vadjustment");
            adj.connect_value_notify(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    if imp.needs_more_items() {
                        spawn!(async move {
                            imp.load_more_items().await;
                        });
                    }
                }
            ));
        }

        /// Load more items in this viewer.
        pub(super) async fn load_more_items(&self) {
            self.timeline
                .obj()
                .load(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    #[upgrade_or]
                    ControlFlow::Break(()),
                    move || {
                        if imp.needs_more_items() {
                            ControlFlow::Continue(())
                        } else {
                            ControlFlow::Break(())
                        }
                    }
                ))
                .await;
        }

        /// Whether this viewer needs more items.
        fn needs_more_items(&self) -> bool {
            let Some(model) = self.list_view.model() else {
                return false;
            };

            // Make sure there is an initial number of items.
            if model.n_items() < MIN_N_ITEMS {
                return true;
            }

            let adj = self
                .list_view
                .vadjustment()
                .expect("GtkListView has a vadjustment");
            adj.value() + adj.page_size() * 2.0 >= adj.upper()
        }

        /// Update this viewer for the current state.
        fn update_state(&self) {
            let Some(model) = self.list_view.model() else {
                return;
            };
            let timeline = self.timeline.obj();

            let visible_child_name = match timeline.state() {
                TimelineState::Initial => "loading",
                TimelineState::Error => "error",
                TimelineState::Complete if model.n_items() == 0 => "empty",
                TimelineState::Loading => {
                    if model.n_items() == 0
                        || (model.n_items() == 1
                            && model.item(0).is_some_and(|item| item.is::<LoadingRow>()))
                    {
                        "loading"
                    } else {
                        "content"
                    }
                }
                _ => "content",
            };
            self.stack.set_visible_child_name(visible_child_name);
        }
    }
}

glib::wrapper! {
    /// A view presenting the list of audio events in a room.
    pub struct AudioHistoryViewer(ObjectSubclass<imp::AudioHistoryViewer>)
        @extends gtk::Widget, adw::NavigationPage;
}

#[gtk::template_callbacks]
impl AudioHistoryViewer {
    pub fn new(timeline: &HistoryViewerTimeline) -> Self {
        glib::Object::builder()
            .property("timeline", timeline)
            .build()
    }

    /// Load more items in this viewer.
    #[template_callback]
    async fn load_more_items(&self) {
        self.imp().load_more_items().await;
    }
}