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
use adw::{prelude::*, subclass::prelude::*};
use gettextrs::gettext;
use gtk::{
    gio,
    glib::{self, clone},
    CompositeTemplate,
};
use tracing::warn;

use super::ContentFormat;
use crate::{
    components::{AudioPlayer, Spinner},
    gettext_f,
    session::model::Session,
    spawn,
    utils::{matrix::MediaMessage, LoadingState},
};

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

    use glib::subclass::InitializingObject;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(
        resource = "/org/gnome/Fractal/ui/session/view/content/room_history/message_row/audio.ui"
    )]
    #[properties(wrapper_type = super::MessageAudio)]
    pub struct MessageAudio {
        /// The filename of the audio file.
        #[property(get)]
        pub filename: RefCell<Option<String>>,
        /// The state of the audio file.
        #[property(get, builder(LoadingState::default()))]
        pub state: Cell<LoadingState>,
        /// Whether to display this audio message in a compact format.
        #[property(get)]
        pub compact: Cell<bool>,
        #[template_child]
        pub player: TemplateChild<AudioPlayer>,
        #[template_child]
        pub state_spinner: TemplateChild<Spinner>,
        #[template_child]
        pub state_error: TemplateChild<gtk::Image>,
    }

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

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

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

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

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

    impl WidgetImpl for MessageAudio {}
    impl BinImpl for MessageAudio {}
}

glib::wrapper! {
    /// A widget displaying an audio message in the timeline.
    pub struct MessageAudio(ObjectSubclass<imp::MessageAudio>)
        @extends gtk::Widget, adw::Bin, @implements gtk::Accessible;
}

impl MessageAudio {
    /// Create a new audio message.
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Set the filename of the audio file.
    fn set_filename(&self, filename: Option<String>) {
        if self.filename() == filename {
            return;
        }

        let accessible_label = if let Some(filename) = &filename {
            gettext_f("Audio: {filename}", &[("filename", filename)])
        } else {
            gettext("Audio")
        };
        self.update_property(&[gtk::accessible::Property::Label(&accessible_label)]);

        self.imp().filename.replace(filename);

        self.notify_filename();
    }

    /// Set the compact format of this audio message.
    fn set_compact(&self, compact: bool) {
        self.imp().compact.set(compact);

        if compact {
            self.remove_css_class("osd");
            self.remove_css_class("toolbar");
        } else {
            self.add_css_class("osd");
            self.add_css_class("toolbar");
        }

        self.notify_compact();
    }

    /// Set the state of the audio file.
    fn set_state(&self, state: LoadingState) {
        let imp = self.imp();

        if self.state() == state {
            return;
        }

        match state {
            LoadingState::Loading | LoadingState::Initial => {
                imp.state_spinner.set_visible(true);
                imp.state_error.set_visible(false);
            }
            LoadingState::Ready => {
                imp.state_spinner.set_visible(false);
                imp.state_error.set_visible(false);
            }
            LoadingState::Error => {
                imp.state_spinner.set_visible(false);
                imp.state_error.set_visible(true);
            }
        }

        imp.state.set(state);
        self.notify_state();
    }

    /// Convenience method to set the state to `Error` with the given error
    /// message.
    fn set_error(&self, error: String) {
        self.set_state(LoadingState::Error);
        self.imp().state_error.set_tooltip_text(Some(&error));
    }

    /// Display the given `audio` message.
    pub fn audio(&self, message: MediaMessage, session: &Session, format: ContentFormat) {
        self.set_filename(Some(message.filename()));

        let compact = matches!(format, ContentFormat::Compact | ContentFormat::Ellipsized);
        self.set_compact(compact);
        if compact {
            self.set_state(LoadingState::Ready);
            return;
        }

        self.set_state(LoadingState::Loading);

        let client = session.client();

        spawn!(
            glib::Priority::LOW,
            clone!(
                #[weak(rename_to = obj)]
                self,
                async move {
                    match message.into_tmp_file(&client).await {
                        Ok(file) => {
                            obj.display_file(file);
                        }
                        Err(error) => {
                            warn!("Could not retrieve audio file: {error}");
                            obj.set_error(gettext("Could not retrieve audio file"));
                        }
                    }
                }
            )
        );
    }

    fn display_file(&self, file: gio::File) {
        let media_file = gtk::MediaFile::for_file(&file);

        media_file.connect_error_notify(clone!(
            #[weak(rename_to = obj)]
            self,
            move |media_file| {
                if let Some(error) = media_file.error() {
                    warn!("Error reading audio file: {error}");
                    obj.set_error(gettext("Error reading audio file"));
                }
            }
        ));

        self.imp().player.set_media_file(Some(media_file));
        self.set_state(LoadingState::Ready);
    }
}

impl Default for MessageAudio {
    fn default() -> Self {
        Self::new()
    }
}