fractal/components/media/
content_viewer.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
use adw::{prelude::*, subclass::prelude::*};
use geo_uri::GeoUri;
use gettextrs::gettext;
use gtk::{gdk, gio, glib, CompositeTemplate};

use super::{AnimatedImagePaintable, AudioPlayer, LocationViewer};
use crate::{
    components::ContextMenuBin,
    prelude::*,
    utils::{media::image::IMAGE_QUEUE, CountedRef, File},
};

/// The types of content supported by the [`MediaContentViewer`].
#[derive(Debug, Default, Clone, Copy)]
pub enum ContentType {
    /// An image.
    Image,
    /// An audio file.
    Audio,
    /// A video.
    Video,
    /// An other content type.
    ///
    /// These types are not supported and will result in a fallback screen.
    #[default]
    Other,
}

impl ContentType {
    /// The name of the icon to represent this content type.
    pub(crate) fn icon_name(self) -> &'static str {
        match self {
            ContentType::Image => "image-symbolic",
            ContentType::Audio => "audio-symbolic",
            ContentType::Video => "video-symbolic",
            ContentType::Other => "document-symbolic",
        }
    }
}

impl From<&str> for ContentType {
    fn from(string: &str) -> Self {
        match string {
            "image" => Self::Image,
            "audio" => Self::Audio,
            "video" => Self::Video,
            _ => Self::Other,
        }
    }
}

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/components/media/content_viewer.ui")]
    #[properties(wrapper_type = super::MediaContentViewer)]
    pub struct MediaContentViewer {
        #[template_child]
        stack: TemplateChild<gtk::Stack>,
        #[template_child]
        viewer: TemplateChild<adw::Bin>,
        #[template_child]
        fallback: TemplateChild<adw::StatusPage>,
        /// Whether to play the media content automatically.
        #[property(get, construct_only)]
        autoplay: Cell<bool>,
        /// The current media file.
        file: RefCell<Option<File>>,
        paintable_animation_ref: RefCell<Option<CountedRef>>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for MediaContentViewer {
        const NAME: &'static str = "MediaContentViewer";
        type Type = super::MediaContentViewer;
        type ParentType = ContextMenuBin;

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

            klass.set_css_name("media-content-viewer");
        }

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

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

    impl WidgetImpl for MediaContentViewer {}
    impl ContextMenuBinImpl for MediaContentViewer {}

    #[gtk::template_callbacks]
    impl MediaContentViewer {
        /// Update the visible child.
        pub(super) fn set_visible_child(&self, name: &str) {
            self.stack.set_visible_child_name(name);
        }

        /// The media child of the given type, if any.
        pub(super) fn media_child<T: IsA<gtk::Widget>>(&self) -> Option<T> {
            self.viewer.child().and_downcast()
        }

        /// Show the fallback message for the given content type.
        pub(super) fn show_fallback(&self, content_type: ContentType) {
            self.file.take();

            let title = match content_type {
                ContentType::Image => gettext("Image not Viewable"),
                ContentType::Audio => gettext("Audio Clip not Playable"),
                ContentType::Video => gettext("Video not Playable"),
                ContentType::Other => gettext("File not Viewable"),
            };
            self.fallback.set_title(&title);
            self.fallback.set_icon_name(Some(content_type.icon_name()));

            self.set_visible_child("fallback");
        }

        /// View the given image as bytes.
        ///
        /// If you have an image file, you can also use
        /// [`MediaContentViewer::view_file()`].
        pub(super) fn view_image(&self, image: &gdk::Paintable) {
            self.set_visible_child("loading");
            self.file.take();

            let picture = if let Some(picture) = self.media_child::<gtk::Picture>() {
                picture
            } else {
                let picture = gtk::Picture::builder()
                    .valign(gtk::Align::Center)
                    .halign(gtk::Align::Center)
                    .build();
                self.viewer.set_child(Some(&picture));
                picture
            };

            picture.set_paintable(Some(image));
            self.update_animated_paintable_state();
            self.set_visible_child("viewer");
        }

        /// View the given file.
        pub(super) async fn view_file(&self, file: File, content_type: Option<ContentType>) {
            self.set_visible_child("loading");
            self.file.replace(Some(file.clone()));

            let content_type = if let Some(content_type) = content_type {
                content_type
            } else {
                let file_info = file
                    .as_gfile()
                    .query_info_future(
                        gio::FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
                        gio::FileQueryInfoFlags::NONE,
                        glib::Priority::DEFAULT,
                    )
                    .await
                    .ok();

                file_info
                    .as_ref()
                    .and_then(gio::FileInfo::content_type)
                    .and_then(|content_type| gio::content_type_get_mime_type(&content_type))
                    .and_then(|mime| mime.split('/').next().map(Into::into))
                    .unwrap_or_default()
            };

            match content_type {
                ContentType::Image => {
                    let handle = IMAGE_QUEUE.add_file_request(file, None).await;
                    if let Ok(image) = handle.await {
                        self.view_image(&gdk::Paintable::from(image));
                        return;
                    }
                }
                ContentType::Audio => {
                    let audio = if let Some(audio) = self.media_child::<AudioPlayer>() {
                        audio
                    } else {
                        let audio = AudioPlayer::new();
                        audio.add_css_class("toolbar");
                        audio.add_css_class("osd");
                        audio.set_autoplay(self.autoplay.get());
                        audio.set_valign(gtk::Align::Center);
                        audio.set_halign(gtk::Align::Center);
                        self.viewer.set_child(Some(&audio));
                        audio
                    };

                    audio.set_file(Some(&file.as_gfile()));
                    self.update_animated_paintable_state();
                    self.set_visible_child("viewer");
                    return;
                }
                ContentType::Video => {
                    let video = if let Some(video) = self.media_child::<gtk::Video>() {
                        video
                    } else {
                        let video = gtk::Video::builder()
                            .autoplay(self.autoplay.get())
                            .valign(gtk::Align::Center)
                            .halign(gtk::Align::Center)
                            .build();
                        self.viewer.set_child(Some(&video));
                        video
                    };

                    video.set_file(Some(&file.as_gfile()));
                    self.update_animated_paintable_state();
                    self.set_visible_child("viewer");
                    return;
                }
                // Other types are not supported.
                ContentType::Other => {}
            }

            self.show_fallback(content_type);
        }

        /// View the given location as a geo URI.
        pub(super) fn view_location(&self, geo_uri: &GeoUri) {
            let location =
                if let Some(location) = self.viewer.child().and_downcast::<LocationViewer>() {
                    location
                } else {
                    let location = LocationViewer::new();
                    self.viewer.set_child(Some(&location));
                    location
                };

            location.set_location(geo_uri);
            self.update_animated_paintable_state();
            self.set_visible_child("viewer");
        }

        /// Update the state of the animated paintable, if any.
        #[template_callback]
        fn update_animated_paintable_state(&self) {
            self.paintable_animation_ref.take();

            let Some(paintable) = self
                .viewer
                .child()
                .and_downcast::<gtk::Picture>()
                .and_then(|p| p.paintable())
                .and_downcast::<AnimatedImagePaintable>()
            else {
                return;
            };

            if self.viewer.is_mapped() {
                self.paintable_animation_ref
                    .replace(Some(paintable.animation_ref()));
            }
        }

        /// Stop the playback, if the media is a video.
        pub(super) fn stop_playback(&self) {
            if let Some(stream) = self
                .media_child::<gtk::Video>()
                .and_then(|v| v.media_stream())
            {
                if stream.is_playing() {
                    stream.pause();
                    stream.seek(0);
                }
            }
        }
    }
}

glib::wrapper! {
    /// Widget to view any media file.
    pub struct MediaContentViewer(ObjectSubclass<imp::MediaContentViewer>)
        @extends gtk::Widget, ContextMenuBin, @implements gtk::Accessible;
}

impl MediaContentViewer {
    pub fn new(autoplay: bool) -> Self {
        glib::Object::builder()
            .property("autoplay", autoplay)
            .build()
    }

    /// Stop the playback, if the media is a video.
    pub(crate) fn stop_playback(&self) {
        self.imp().stop_playback();
    }

    /// Show the loading screen.
    pub(crate) fn show_loading(&self) {
        self.imp().set_visible_child("loading");
    }

    /// Show the fallback message for the given content type.
    pub(crate) fn show_fallback(&self, content_type: ContentType) {
        self.imp().show_fallback(content_type);
    }

    /// View the given image as bytes.
    ///
    /// If you have an image file, you can also use
    /// [`MediaContentViewer::view_file()`].
    pub(crate) fn view_image(&self, image: &impl IsA<gdk::Paintable>) {
        self.imp().view_image(image.upcast_ref());
    }

    /// View the given file.
    ///
    /// If the content type is not provided, it will be guessed from the file.
    pub(crate) async fn view_file(&self, file: File, content_type: Option<ContentType>) {
        self.imp().view_file(file, content_type).await;
    }

    /// View the given location as a geo URI.
    pub(crate) fn view_location(&self, geo_uri: &GeoUri) {
        self.imp().view_location(geo_uri);
    }

    /// Get the texture displayed by this widget, if any.
    pub(crate) fn texture(&self) -> Option<gdk::Texture> {
        let paintable = self
            .imp()
            .media_child::<gtk::Picture>()
            .and_then(|p| p.paintable())?;

        if let Some(paintable) = paintable.downcast_ref::<AnimatedImagePaintable>() {
            paintable.current_texture()
        } else {
            paintable.downcast::<gdk::Texture>().ok()
        }
    }
}