Skip to main content

cosmic_applet_avestruz/views/components/
picture.rs

1// SPDX-License-Identifier: MIT
2
3//! A picture in a note: as wide as its row and no wider than it is, as
4//! tall as its proportions make it, and drawn pixel for pixel where it
5//! can be.
6//!
7//! What draws a frame is a CPU renderer, and of all it does, scaling a
8//! picture costs the most. A picture is therefore kept at the size it is
9//! shown at (see [`crate::images`]), and this widget draws it as it is
10//! kept: where the pixels kept are the pixels its room takes, each is
11//! taken as it is, and where they aren't (a row narrower than the widest,
12//! a screen that turned out another scale than the picture was made for)
13//! it is scaled as any picture is, smoothly, and slower.
14//!
15//! It is laid out by the size of the picture itself and not by what is
16//! kept of it, which is rounded to whole pixels: the room it takes is the
17//! room that was kept for it when its note said how large it is.
18//!
19//! iced's own picture widget asks the renderer how large the picture is
20//! when it is laid out, for which the renderer makes its own copy of it
21//! there and then; it draws it smoothly whatever its size; and it takes
22//! its proportions from the pixels. This one is told its size.
23//!
24//! A click on a picture is a click on its row, and the picture takes none
25//! of them but one: with the right button, if it was told what that does.
26//! The toolkit's own way of hearing a click, an area around a widget,
27//! takes every press of the left button for itself, whether it was told
28//! what one does or not, and the row would hear of none.
29
30use cosmic::iced::core::image::{self, FilterMethod};
31use cosmic::iced::core::layout;
32use cosmic::iced::core::mouse;
33use cosmic::iced::core::renderer;
34use cosmic::iced::core::widget::Tree;
35use cosmic::iced::core::{Clipboard, Element, Event, Layout, Length, Radians, Rectangle, Shell, Size, Widget, border};
36use cosmic::widget::image::Handle;
37
38use crate::images::LoadedImage;
39
40/// How far, in pixels, what is kept of a picture may be from the room it
41/// is drawn in and still be drawn pixel for pixel: less than one. A row is
42/// seldom a whole number of pixels wide, and the picture kept is.
43const SAME_SIZE: f32 = 1.0;
44
45/// A picture in a note. See the [module docs](self).
46pub struct Picture<Message> {
47    handle: Handle,
48    /// How large the picture itself is: what it is laid out by.
49    size: Size,
50    radius: f32,
51    /// What a click on it with the right button does, if anything.
52    on_right_press: Option<Message>,
53}
54
55impl<Message> Picture<Message> {
56    /// `loaded`, with square corners.
57    pub fn new(loaded: &LoadedImage) -> Self {
58        Self {
59            handle: loaded.handle.clone(),
60            size: Size::new(loaded.width.max(1) as f32, loaded.height.max(1) as f32),
61            radius: 0.0,
62            on_right_press: None,
63        }
64    }
65
66    /// Its corners rounded by `radius`.
67    pub fn radius(mut self, radius: f32) -> Self {
68        self.radius = radius;
69        self
70    }
71
72    /// A click on it with the right button says `message`.
73    pub fn on_right_press(mut self, message: Message) -> Self {
74        self.on_right_press = Some(message);
75        self
76    }
77}
78
79/// How large a picture `size` large is shown in a row `width` wide: as
80/// wide as the row and no wider than it is, in its own proportions.
81fn shown(size: Size, width: f32) -> Size {
82    let across = width.min(size.width);
83    Size::new(across, across * size.height / size.width)
84}
85
86/// How a picture kept at `kept` pixels is drawn in room of `room` pixels:
87/// each pixel as it is, if they are the same size, and smoothly if not.
88fn filter(kept: Size<u32>, room: Size) -> FilterMethod {
89    let same = (kept.width as f32 - room.width).abs() < SAME_SIZE && (kept.height as f32 - room.height).abs() < SAME_SIZE;
90    if same { FilterMethod::Nearest } else { FilterMethod::Linear }
91}
92
93impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Picture<Message>
94where
95    Message: Clone,
96    Renderer: image::Renderer<Handle = Handle>,
97{
98    fn size(&self) -> Size<Length> {
99        Size::new(Length::Fill, Length::Shrink)
100    }
101
102    fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
103        layout::Node::new(shown(self.size, limits.max().width))
104    }
105
106    fn update(
107        &mut self,
108        _tree: &mut Tree,
109        event: &Event,
110        layout: Layout<'_>,
111        cursor: mouse::Cursor,
112        _renderer: &Renderer,
113        _clipboard: &mut dyn Clipboard,
114        shell: &mut Shell<'_, Message>,
115        _viewport: &Rectangle,
116    ) {
117        let right_press = matches!(event, Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right)));
118        if let Some(message) = self.on_right_press.as_ref().filter(|_| right_press && cursor.is_over(layout.bounds())) {
119            shell.publish(message.clone());
120            shell.capture_event();
121        }
122    }
123
124    fn draw(
125        &self,
126        _tree: &Tree,
127        renderer: &mut Renderer,
128        _theme: &Theme,
129        style: &renderer::Style,
130        layout: Layout<'_>,
131        _cursor: mouse::Cursor,
132        _viewport: &Rectangle,
133    ) {
134        let bounds = layout.bounds();
135        let scale = style.scale_factor as f32;
136        let filter_method = match &self.handle {
137            Handle::Rgba { width, height, .. } => {
138                filter(Size::new(*width, *height), Size::new(bounds.width * scale, bounds.height * scale))
139            }
140            _ => FilterMethod::Linear,
141        };
142        renderer.draw_image(
143            image::Image {
144                handle: self.handle.clone(),
145                filter_method,
146                rotation: Radians(0.0),
147                border_radius: border::Radius::from(self.radius),
148                opacity: 1.0,
149                snap: true,
150            },
151            bounds,
152            bounds,
153        );
154    }
155}
156
157impl<'a, Message, Theme, Renderer> From<Picture<Message>> for Element<'a, Message, Theme, Renderer>
158where
159    Message: Clone + 'a,
160    Renderer: image::Renderer<Handle = Handle> + 'a,
161{
162    fn from(picture: Picture<Message>) -> Self {
163        Element::new(picture)
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::{Picture, filter, shown};
170    use crate::images::LoadedImage;
171    use cosmic::iced::core::image::FilterMethod;
172    use cosmic::iced::core::widget::Tree;
173    use cosmic::iced::core::{Event, Layout, Point, Rectangle, Shell, Widget, clipboard, layout, mouse};
174    use cosmic::iced::{Length, Size};
175    use cosmic::widget::image::Handle;
176
177    #[test]
178    fn a_picture_takes_a_click_with_the_right_button_and_no_other() {
179        let loaded = LoadedImage { handle: Handle::from_rgba(2, 1, vec![0; 8]), width: 200, height: 100 };
180        let mut picture: Picture<&str> = Picture::new(&loaded).on_right_press("copy");
181        let renderer = crate::views::components::testing::renderer();
182        let widget: &mut dyn Widget<&str, cosmic::Theme, cosmic::Renderer> = &mut picture;
183        assert_eq!(widget.size().width, Length::Fill);
184        let mut tree = Tree::empty();
185        let node = widget.layout(&mut tree, &renderer, &layout::Limits::new(Size::ZERO, Size::new(600.0, 900.0)));
186        assert_eq!(node.size(), Size::new(200.0, 100.0));
187
188        // What a press of `button` at `at` says, and whether the picture
189        // took it for itself.
190        let mut pressed = |button: mouse::Button, at: Point| {
191            let mut said = Vec::new();
192            let mut shell = Shell::new(&mut said);
193            widget.update(
194                &mut tree,
195                &Event::Mouse(mouse::Event::ButtonPressed(button)),
196                Layout::new(&node),
197                mouse::Cursor::Available(at),
198                &renderer,
199                &mut clipboard::Null,
200                &mut shell,
201                &Rectangle::new(Point::ORIGIN, Size::new(600.0, 900.0)),
202            );
203            let taken = shell.is_event_captured();
204            (said, taken)
205        };
206        let (on_it, beside_it) = (Point::new(100.0, 50.0), Point::new(300.0, 50.0));
207        assert_eq!(pressed(mouse::Button::Right, on_it), (vec!["copy"], true));
208        assert_eq!(pressed(mouse::Button::Right, beside_it), (vec![], false), "beside it, in the room it leaves");
209        // The left button is the row's: the picture neither answers nor takes it.
210        assert_eq!(pressed(mouse::Button::Left, on_it), (vec![], false));
211    }
212
213    #[test]
214    fn a_picture_is_as_wide_as_its_row_no_wider_than_itself_and_in_its_own_proportions() {
215        // Wider than its row: the row's width.
216        assert_eq!(shown(Size::new(4_000.0, 3_000.0), 600.0), Size::new(600.0, 450.0));
217        // Narrower: its own size, a point to the pixel.
218        assert_eq!(shown(Size::new(300.0, 100.0), 600.0), Size::new(300.0, 100.0));
219        // Taller than it is wide: as tall as that makes it.
220        assert_eq!(shown(Size::new(1_000.0, 2_000.0), 600.0), Size::new(600.0, 1_200.0));
221    }
222
223    #[test]
224    fn a_picture_kept_at_the_size_of_its_room_is_drawn_pixel_for_pixel() {
225        // A row 614 points wide at 170% is 1043.8 pixels: the picture was
226        // kept at 1044, and what is kept is what is drawn.
227        assert_eq!(filter(Size::new(1_044, 783), Size::new(1_043.8, 782.85)), FilterMethod::Nearest);
228        assert_eq!(filter(Size::new(614, 460), Size::new(614.0, 460.5)), FilterMethod::Nearest);
229        // In a narrower row, or on a screen of another scale than it was
230        // made for, it is scaled, and smoothly.
231        assert_eq!(filter(Size::new(1_044, 783), Size::new(900.0, 675.0)), FilterMethod::Linear);
232        assert_eq!(filter(Size::new(614, 460), Size::new(1_043.8, 782.9)), FilterMethod::Linear);
233        assert_eq!(filter(Size::new(1_044, 783), Size::new(1_043.8, 700.0)), FilterMethod::Linear);
234    }
235}