Skip to main content

cosmic_applet_avestruz/views/components/
media_placeholder.rs

1// SPDX-License-Identifier: MIT
2
3//! The space a picture will take, held while it loads.
4//!
5//! A note's image arrives after the note does. If its row grew when it did,
6//! everything below would jump. [`MediaPlaceholder`] takes the room the
7//! picture will take once it is there, when the note says how large the
8//! picture is (NIP-92 `imeta`), so the row is the same height before and
9//! after.
10//!
11//! A picture is shown as wide as the room there is for it, from one edge
12//! to the other, and as tall as that makes it; but never larger than it
13//! is: one narrower than the room keeps its own size. [`shown_size`] is
14//! that rule, for the placeholder, the picture and the estimate of a row's
15//! height alike.
16
17use cosmic::iced::core::layout;
18use cosmic::iced::core::mouse;
19use cosmic::iced::core::renderer;
20use cosmic::iced::core::widget::Tree;
21use cosmic::iced::core::{Border, Color, Element, Layout, Length, Rectangle, Size, Widget};
22
23/// How large a picture is shown, given its size in pixels and the width
24/// there is for it: scaled down to that width, as tall as that makes it,
25/// and never scaled up.
26///
27/// This is what the image widget does with `ContentFit::Contain`, a `Fill`
28/// width that stops at the picture's own and a `Shrink` height, written out
29/// so that the placeholder and the estimate of a row's height agree with it.
30pub fn shown_size(size: (u32, u32), width: f32) -> Size {
31    let (w, h) = (size.0.max(1) as f32, size.1.max(1) as f32);
32    let across = width.min(w);
33    Size::new(across, h * (across / w))
34}
35
36/// A quiet rounded box where a picture is about to be.
37pub struct MediaPlaceholder {
38    /// The picture's size in pixels, if the note said.
39    size: Option<(u32, u32)>,
40    /// How tall to be when the size isn't known.
41    fallback_height: f32,
42    radius: f32,
43}
44
45impl MediaPlaceholder {
46    /// A placeholder for a picture of `size` pixels, if known: as large as
47    /// the picture will be shown. As wide as the room there is and
48    /// `fallback_height` tall otherwise.
49    pub fn new(size: Option<(u32, u32)>, fallback_height: f32) -> Self {
50        Self { size, fallback_height, radius: 0.0 }
51    }
52
53    /// Round the corners, as the picture's will be.
54    pub fn radius(mut self, radius: f32) -> Self {
55        self.radius = radius;
56        self
57    }
58}
59
60impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for MediaPlaceholder
61where
62    Renderer: renderer::Renderer,
63{
64    fn size(&self) -> Size<Length> {
65        Size::new(Length::Fill, Length::Shrink)
66    }
67
68    fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
69        let width = limits.max().width;
70        layout::Node::new(match self.size {
71            Some(size) => shown_size(size, width),
72            None => Size::new(width, self.fallback_height),
73        })
74    }
75
76    fn draw(
77        &self,
78        _tree: &Tree,
79        renderer: &mut Renderer,
80        _theme: &Theme,
81        style: &renderer::Style,
82        layout: Layout<'_>,
83        _cursor: mouse::Cursor,
84        _viewport: &Rectangle,
85    ) {
86        // The text colour, faint: visible on a light theme and a dark one.
87        let fill = Color { a: 0.08, ..style.text_color };
88        renderer.fill_quad(
89            renderer::Quad {
90                bounds: layout.bounds(),
91                border: Border { radius: self.radius.into(), ..Border::default() },
92                ..renderer::Quad::default()
93            },
94            fill,
95        );
96    }
97}
98
99impl<'a, Message, Theme, Renderer> From<MediaPlaceholder> for Element<'a, Message, Theme, Renderer>
100where
101    Renderer: renderer::Renderer,
102{
103    fn from(placeholder: MediaPlaceholder) -> Self {
104        Element::new(placeholder)
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::{MediaPlaceholder, shown_size};
111    use cosmic::iced::core::widget::Tree;
112    use cosmic::iced::core::{Element, Size, layout};
113
114    fn laid_out(placeholder: MediaPlaceholder, width: f32) -> Size {
115        let mut element: Element<'_, (), (), ()> = placeholder.into();
116        let mut tree = Tree::new(element.as_widget());
117        let limits = layout::Limits::new(Size::ZERO, Size::new(width, f32::INFINITY));
118        element.as_widget_mut().layout(&mut tree, &(), &limits).size()
119    }
120
121    #[test]
122    fn a_picture_is_as_wide_as_the_room_there_is_and_never_larger_than_it_is() {
123        // Wider than the room: scaled to the width.
124        assert_eq!(shown_size((1200, 800), 300.0), Size::new(300.0, 200.0));
125        // Tall: as wide as the room all the same, however tall that is.
126        assert_eq!(shown_size((600, 1800), 300.0), Size::new(300.0, 900.0));
127        // Just as wide as the room: as it is.
128        assert_eq!(shown_size((300, 150), 300.0), Size::new(300.0, 150.0));
129        // Small: never scaled up.
130        assert_eq!(shown_size((100, 50), 300.0), Size::new(100.0, 50.0));
131        // Nonsense sizes don't divide by zero.
132        assert_eq!(shown_size((0, 0), 300.0), Size::new(1.0, 1.0));
133    }
134
135    #[test]
136    fn the_placeholder_is_as_large_as_the_picture_will_be() {
137        assert_eq!(laid_out(MediaPlaceholder::new(Some((1200, 800)), 180.0), 300.0), Size::new(300.0, 200.0));
138        assert_eq!(laid_out(MediaPlaceholder::new(Some((600, 1800)), 180.0), 300.0), Size::new(300.0, 900.0));
139        assert_eq!(laid_out(MediaPlaceholder::new(Some((100, 50)), 180.0), 300.0), Size::new(100.0, 50.0));
140        assert_eq!(laid_out(MediaPlaceholder::new(None, 180.0), 300.0), Size::new(300.0, 180.0));
141    }
142}