fractal/session/view/content/room_history/message_row/
visual_media.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
use adw::{prelude::*, subclass::prelude::*};
use gettextrs::gettext;
use gtk::{
    gdk,
    glib::{self, clone},
    CompositeTemplate,
};
use matrix_sdk::Client;
use ruma::api::client::media::get_content_thumbnail::v3::Method;
use tracing::{error, warn};

use super::{content::MessageCacheKey, ContentFormat};
use crate::{
    components::{AnimatedImagePaintable, VideoPlayer},
    gettext_f,
    session::model::Session,
    spawn,
    utils::{
        matrix::VisualMediaMessage,
        media::{
            image::{ImageRequestPriority, ThumbnailSettings, THUMBNAIL_MAX_DIMENSIONS},
            FrameDimensions,
        },
        CountedRef, File, LoadingState,
    },
};

/// The dimensions to use for the media until we know its size.
const FALLBACK_DIMENSIONS: FrameDimensions = FrameDimensions {
    width: 480,
    height: 360,
};
/// The maximum dimensions allowed for the media in its compact form.
const MAX_COMPACT_DIMENSIONS: FrameDimensions = FrameDimensions {
    width: 75,
    height: 50,
};
/// The name of the media stack page.
const MEDIA_PAGE: &str = "media";

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/visual_media.ui"
    )]
    #[properties(wrapper_type = super::MessageVisualMedia)]
    pub struct MessageVisualMedia {
        #[template_child]
        overlay: TemplateChild<gtk::Overlay>,
        #[template_child]
        stack: TemplateChild<gtk::Stack>,
        #[template_child]
        spinner: TemplateChild<adw::Spinner>,
        #[template_child]
        error: TemplateChild<gtk::Image>,
        /// The supposed dimensions of the media.
        dimensions: Cell<Option<FrameDimensions>>,
        /// The loading state of the media.
        #[property(get, builder(LoadingState::default()))]
        state: Cell<LoadingState>,
        /// Whether to display this media in a compact format.
        #[property(get)]
        compact: Cell<bool>,
        /// Whether the media can be activated.
        ///
        /// If the media is activatable and it is not using the compact format,
        /// clicking on the media opens the media viewer.
        #[property(get)]
        activatable: Cell<bool>,
        gesture_click: glib::WeakRef<gtk::GestureClick>,
        /// The cache key for the current media message.
        ///
        /// We only try to reload the media if the key changes. This is to avoid
        /// reloading the media when a local echo changes to a remote echo.
        cache_key: RefCell<MessageCacheKey>,
        /// The current video file, if any.
        file: RefCell<Option<File>>,
        paintable_animation_ref: RefCell<Option<CountedRef>>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for MessageVisualMedia {
        const NAME: &'static str = "ContentMessageVisualMedia";
        type Type = super::MessageVisualMedia;
        type ParentType = gtk::Widget;

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

            klass.set_css_name("message-visual-media");
            klass.set_accessible_role(gtk::AccessibleRole::Group);
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for MessageVisualMedia {
        fn dispose(&self) {
            self.overlay.unparent();
        }
    }

    impl WidgetImpl for MessageVisualMedia {
        fn measure(&self, orientation: gtk::Orientation, for_size: i32) -> (i32, i32, i32, i32) {
            // Get the maximum size for the current state.
            let max_size = if self.compact.get() {
                MAX_COMPACT_DIMENSIONS
            } else {
                THUMBNAIL_MAX_DIMENSIONS
            };
            let max = max_size.dimension_for_orientation(orientation);
            let max_for_size = max_size
                .dimension_for_other_orientation(orientation)
                .try_into()
                .unwrap_or(i32::MAX);

            // Limit for_size to the max.
            let for_size = if for_size == -1 {
                // -1 means unlimited.
                max_for_size
            } else {
                for_size.min(max_for_size)
            };

            // Use the size measured by the media child when we can, it is the natural size
            // of the media.
            if self.stack.visible_child_name().as_deref() == Some(MEDIA_PAGE) {
                if let Some(child) = self.media_child::<gtk::Widget>() {
                    // Get the intrinsic size of the media to avoid upscaling it. It is the size
                    // returned by GtkPicture when for_size is -1.
                    let other_orientation = if orientation == gtk::Orientation::Vertical {
                        gtk::Orientation::Horizontal
                    } else {
                        gtk::Orientation::Vertical
                    };
                    let (_, intrinsic_for_size, ..) = child.measure(other_orientation, -1);

                    let (min, nat, ..) =
                        child.measure(orientation, for_size.min(intrinsic_for_size));

                    if nat != 0 {
                        // Limit the returned size to the max.
                        let max = max.try_into().unwrap_or(i32::MAX);

                        return (min.min(max), nat.min(max), -1, -1);
                    }
                }
            }

            // Limit the wanted size to the max size.
            let for_size = u32::try_from(for_size).unwrap_or(0);
            let wanted_size = if orientation == gtk::Orientation::Vertical {
                FrameDimensions {
                    width: for_size,
                    height: max,
                }
            } else {
                FrameDimensions {
                    width: max,
                    height: for_size,
                }
            };

            // Use the size from the info or the fallback size.
            let media_size = self.dimensions.get().unwrap_or(FALLBACK_DIMENSIONS);
            let nat = media_size
                .scale_to_fit(wanted_size, gtk::ContentFit::ScaleDown)
                .dimension_for_orientation(orientation)
                .try_into()
                .unwrap_or(i32::MAX);

            (0, nat, -1, -1)
        }

        fn request_mode(&self) -> gtk::SizeRequestMode {
            gtk::SizeRequestMode::HeightForWidth
        }

        fn size_allocate(&self, width: i32, height: i32, baseline: i32) {
            self.overlay.allocate(width, height, baseline, None);
        }

        fn map(&self) {
            self.parent_map();
            self.update_animated_paintable_state();
        }

        fn unmap(&self) {
            self.parent_unmap();
            self.update_animated_paintable_state();
        }
    }

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

        /// Set the media child.
        ///
        /// Removes the previous media child if one was set.
        fn set_media_child(&self, child: &impl IsA<gtk::Widget>) {
            if let Some(prev_child) = self.stack.child_by_name(MEDIA_PAGE) {
                self.stack.remove(&prev_child);
            }

            self.stack.add_named(child, Some(MEDIA_PAGE));
        }

        /// Set the state of the media.
        fn set_state(&self, state: LoadingState) {
            if self.state.get() == state {
                return;
            }

            match state {
                LoadingState::Loading | LoadingState::Initial => {
                    self.stack.set_visible_child_name("placeholder");
                    self.spinner.set_visible(true);
                    self.error.set_visible(false);
                }
                LoadingState::Ready => {
                    self.stack.set_visible_child_name(MEDIA_PAGE);
                    self.spinner.set_visible(false);
                    self.error.set_visible(false);
                }
                LoadingState::Error => {
                    self.spinner.set_visible(false);
                    self.error.set_visible(true);
                }
            }

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

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

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

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

        /// Set whether to display this media in a compact format.
        fn set_compact(&self, compact: bool) {
            if self.compact.get() == compact {
                return;
            }

            self.compact.set(compact);

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

            self.update_gesture_click();
            self.obj().notify_compact();
        }

        /// Set whether the media can be activated.
        fn set_activatable(&self, activatable: bool) {
            if self.activatable.get() == activatable {
                return;
            }

            self.activatable.set(activatable);

            self.update_gesture_click();
            self.obj().notify_activatable();
        }

        /// Add or remove the click controller given the current state.
        fn update_gesture_click(&self) {
            let needs_controller = self.activatable.get() && !self.compact.get();
            let gesture_click = self.gesture_click.upgrade();

            if needs_controller && gesture_click.is_none() {
                let gesture_click = gtk::GestureClick::new();

                gesture_click.connect_released(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_, _, _, _| {
                        if imp
                            .obj()
                            .activate_action("message-row.show-media", None)
                            .is_err()
                        {
                            error!("Could not activate `message-row.show-media` action");
                        }
                    }
                ));

                self.gesture_click.set(Some(&gesture_click));
                self.overlay.add_controller(gesture_click);
            } else if let Some(gesture_click) = gesture_click {
                self.gesture_click.set(None);
                self.overlay.remove_controller(&gesture_click);
            }
        }

        /// Set the cache key with the given value.
        ///
        /// Returns `true` if the media should be reloaded.
        fn set_cache_key(&self, key: MessageCacheKey) -> bool {
            let should_reload = self.cache_key.borrow().should_reload(&key);

            self.cache_key.replace(key);

            should_reload
        }

        /// Build the content for the given media message.
        pub(super) fn build(
            &self,
            media_message: VisualMediaMessage,
            session: &Session,
            format: ContentFormat,
            cache_key: MessageCacheKey,
        ) {
            if !self.set_cache_key(cache_key) {
                // We do not need to reload the media.
                return;
            }

            self.file.take();
            self.dimensions.set(media_message.dimensions());

            let compact = matches!(format, ContentFormat::Compact | ContentFormat::Ellipsized);
            self.set_compact(compact);

            let activatable = matches!(
                media_message,
                VisualMediaMessage::Image(_) | VisualMediaMessage::Video(_)
            );
            self.set_activatable(activatable);

            let filename = media_message.filename();
            let accessible_label = if filename.is_empty() {
                match &media_message {
                    VisualMediaMessage::Image(_) => gettext("Image"),
                    VisualMediaMessage::Sticker(_) => gettext("Sticker"),
                    VisualMediaMessage::Video(_) => gettext("Video"),
                }
            } else {
                match &media_message {
                    VisualMediaMessage::Image(_) => {
                        gettext_f("Image: {filename}", &[("filename", &filename)])
                    }
                    VisualMediaMessage::Sticker(_) => {
                        gettext_f("Sticker: {filename}", &[("filename", &filename)])
                    }
                    VisualMediaMessage::Video(_) => {
                        gettext_f("Video: {filename}", &[("filename", &filename)])
                    }
                }
            };
            self.obj()
                .update_property(&[gtk::accessible::Property::Label(&accessible_label)]);

            self.set_state(LoadingState::Loading);

            let client = session.client();
            spawn!(
                glib::Priority::LOW,
                clone!(
                    #[weak(rename_to = imp)]
                    self,
                    async move {
                        match &media_message {
                            VisualMediaMessage::Image(_) | VisualMediaMessage::Sticker(_) => {
                                imp.build_image(&media_message, client).await;
                            }
                            VisualMediaMessage::Video(_) => {
                                imp.build_video(media_message, &client).await;
                            }
                        }

                        imp.update_animated_paintable_state();
                    }
                )
            );
        }

        /// Build the content for the image in the given media message.
        async fn build_image(&self, media_message: &VisualMediaMessage, client: Client) {
            // Disable the copy-image action while the image is loading.
            if matches!(media_message, VisualMediaMessage::Image(_)) {
                self.enable_copy_image_action(false);
            }

            let scale_factor = self.obj().scale_factor();

            let settings = ThumbnailSettings {
                dimensions: FrameDimensions::thumbnail_max_dimensions(scale_factor),
                method: Method::Scale,
                animated: true,
                prefer_thumbnail: false,
            };

            let image = match media_message
                .thumbnail(client, settings, ImageRequestPriority::Default)
                .await
            {
                Ok(Some(image)) => image,
                Ok(None) => unreachable!("Image messages should always have a fallback"),
                Err(error) => {
                    self.set_error(&error.to_string());
                    return;
                }
            };

            let child = if let Some(child) = self.media_child::<gtk::Picture>() {
                child
            } else {
                let child = gtk::Picture::builder()
                    .content_fit(gtk::ContentFit::ScaleDown)
                    .build();
                self.set_media_child(&child);
                child
            };
            child.set_paintable(Some(&gdk::Paintable::from(image)));

            child.set_tooltip_text(Some(&media_message.filename()));
            if matches!(&media_message, VisualMediaMessage::Sticker(_)) {
                self.overlay.remove_css_class("opaque-bg");
            } else {
                self.overlay.add_css_class("opaque-bg");
            }

            self.set_state(LoadingState::Ready);

            // Enable the copy-image action now that the image is loaded.
            if matches!(media_message, VisualMediaMessage::Image(_)) {
                self.enable_copy_image_action(true);
            }
        }

        /// Enable or disable the context menu action to copy the image.
        fn enable_copy_image_action(&self, enable: bool) {
            if self.compact.get() {
                // In its compact form the message does not have actions.
                return;
            }

            if self
                .obj()
                .activate_action(
                    "room-history-row.enable-copy-image",
                    Some(&enable.to_variant()),
                )
                .is_err()
            {
                error!("Could not change state of copy-image action: `room-history-row.enable-copy-image` action not found");
            }
        }

        /// Build the content for the video in the given media message.
        async fn build_video(&self, media_message: VisualMediaMessage, client: &Client) {
            let file = match media_message.into_tmp_file(client).await {
                Ok(file) => file,
                Err(error) => {
                    warn!("Could not retrieve video: {error}");
                    self.set_error(&gettext("Could not retrieve media"));
                    return;
                }
            };

            let child = if let Some(child) = self.media_child::<VideoPlayer>() {
                child
            } else {
                let child = VideoPlayer::new();
                child.connect_state_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |player| {
                        imp.video_state_changed(player);
                    }
                ));
                self.set_media_child(&child);
                child
            };

            child.set_compact(self.compact.get());
            child.play_video_file(file.as_gfile());
            self.file.replace(Some(file));
        }

        /// Set the given error message for this media.
        fn set_error(&self, message: &str) {
            self.error.set_tooltip_text(Some(message));
            self.set_state(LoadingState::Error);
        }

        /// Handle when the state of the video changed.
        fn video_state_changed(&self, player: &VideoPlayer) {
            match player.state() {
                LoadingState::Initial | LoadingState::Loading => {
                    self.set_state(LoadingState::Loading);
                }
                LoadingState::Ready => self.set_state(LoadingState::Ready),
                LoadingState::Error => {
                    let error = player.error();
                    self.set_error(
                        error
                            .map(|e| e.to_string())
                            .as_deref()
                            .unwrap_or(&gettext("An unexpected error occurred")),
                    );
                }
            }
        }
    }
}

glib::wrapper! {
    /// A widget displaying a visual media (image or video) message in the timeline.
    pub struct MessageVisualMedia(ObjectSubclass<imp::MessageVisualMedia>)
        @extends gtk::Widget, @implements gtk::Accessible;
}

impl MessageVisualMedia {
    /// Create a new visual media message.
    pub(crate) fn new() -> Self {
        glib::Object::new()
    }

    /// Display the given visual media message.
    pub(crate) fn set_media_message(
        &self,
        media_message: VisualMediaMessage,
        session: &Session,
        format: ContentFormat,
        cache_key: MessageCacheKey,
    ) {
        self.imp().build(media_message, session, format, cache_key);
    }

    /// 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().ok()
        }
    }
}

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