Skip to main content

mln_style/
image.rs

1//! A style's images: an icon or pattern with its pixels, pixel ratio,
2//! stretch areas and content box, from a sprite or added by the app.
3
4use crate::bitmap::PremultipliedImage;
5use crate::error::Error;
6use crate::size::Size;
7
8pub type ImageStretch = (f32, f32);
9pub type ImageStretches = Vec<ImageStretch>;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, mln_wire::Wire)]
12pub enum TextFit {
13    StretchOrShrink,
14    StretchOnly,
15    Proportional,
16}
17
18#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
19pub struct ImageContent {
20    pub left: f32,
21    pub top: f32,
22    pub right: f32,
23    pub bottom: f32,
24}
25
26/// An image in a style, by the ID that layers name it with.
27#[derive(Clone, Debug, mln_wire::Wire)]
28pub struct StyleImage {
29    pub id: String,
30    pub image: PremultipliedImage,
31    /// Pixel ratio of the sprite image.
32    pub pixel_ratio: f32,
33    /// Whether this image should be interpreted as a signed distance field
34    /// icon.
35    pub sdf: bool,
36    /// Stretch areas of this image.
37    pub stretch_x: ImageStretches,
38    pub stretch_y: ImageStretches,
39    /// The space where text can be fit into this image.
40    pub content: Option<ImageContent>,
41    /// If `icon-text-fit` is used in a layer with this image, this option
42    /// defines constraints on the horizontal scaling of the image.
43    pub text_fit_width: Option<TextFit>,
44    /// If `icon-text-fit` is used in a layer with this image, this option
45    /// defines constraints on the vertical scaling of the image.
46    pub text_fit_height: Option<TextFit>,
47    /// Whether the image stays in its style once no layer uses it, whatever
48    /// the map's policy for unused images says.
49    pub keep_unused: bool,
50}
51
52fn validate_stretch(stretches: &ImageStretches, size: f32) -> bool {
53    if stretches.is_empty() {
54        return true;
55    }
56    let mut last = 0.0f32;
57    for part in stretches {
58        if part.0 < last || part.1 < part.0 || size < part.1 {
59            return false;
60        }
61        last = part.1;
62    }
63    true
64}
65
66fn validate_content(content: &ImageContent, size: Size) -> bool {
67    let (width, height) = (size.width as f32, size.height as f32);
68    if content.left < 0.0 || width < content.left {
69        return false;
70    }
71    if content.top < 0.0 || height < content.top {
72        return false;
73    }
74    if content.right < 0.0 || width < content.right {
75        return false;
76    }
77    if content.bottom < 0.0 || height < content.bottom {
78        return false;
79    }
80    if content.right < content.left {
81        return false;
82    }
83    if content.bottom < content.top {
84        return false;
85    }
86    true
87}
88
89impl StyleImage {
90    /// Creates an image. Fails with
91    /// [`ErrorKind::InvalidArgument`](crate::error::ErrorKind) for an empty image,
92    /// a pixel ratio that isn't positive, or stretches or a content area
93    /// outside the image.
94    #[expect(clippy::too_many_arguments, reason = "each argument is a field of the image")]
95    pub fn new(
96        id: String,
97        image: PremultipliedImage,
98        pixel_ratio: f32,
99        sdf: bool,
100        stretch_x: ImageStretches,
101        stretch_y: ImageStretches,
102        content: Option<ImageContent>,
103        text_fit_width: Option<TextFit>,
104        text_fit_height: Option<TextFit>,
105    ) -> Result<Self, Error> {
106        if !image.valid() {
107            return Err(Error::invalid_argument("dimensions may not be zero"));
108        } else if pixel_ratio <= 0.0 {
109            return Err(Error::invalid_argument("pixelRatio may not be <= 0"));
110        } else if !validate_stretch(&stretch_x, image.size.width as f32) {
111            return Err(Error::invalid_argument("stretchX is out of bounds or overlapping"));
112        } else if !validate_stretch(&stretch_y, image.size.height as f32) {
113            return Err(Error::invalid_argument("stretchY is out of bounds or overlapping"));
114        } else if content.as_ref().is_some_and(|content| !validate_content(content, image.size)) {
115            return Err(Error::invalid_argument("content area is invalid"));
116        }
117        Ok(StyleImage {
118            id,
119            image,
120            pixel_ratio,
121            sdf,
122            stretch_x,
123            stretch_y,
124            content,
125            text_fit_width,
126            text_fit_height,
127            keep_unused: false,
128        })
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    /// An image of `width` by `height` pixels, with no `sdf` or text fit.
137    fn image(
138        (width, height): (u32, u32),
139        pixel_ratio: f32,
140        stretch_x: ImageStretches,
141        stretch_y: ImageStretches,
142        content: Option<ImageContent>,
143    ) -> Result<StyleImage, String> {
144        let pixels = PremultipliedImage::new(Size::new(width, height));
145        StyleImage::new("test".to_owned(), pixels, pixel_ratio, false, stretch_x, stretch_y, content, None, None)
146            .map_err(|error| error.message)
147    }
148
149    fn content(left: f32, top: f32, right: f32, bottom: f32) -> ImageContent {
150        ImageContent { left, top, right, bottom }
151    }
152
153    #[test]
154    fn an_invalid_image_is_refused_with_a_reason() {
155        let stretch_x = "stretchX is out of bounds or overlapping";
156        let stretch_y = "stretchY is out of bounds or overlapping";
157        for (name, result, error) in [
158            ("no width", image((0, 16), 2.0, vec![], vec![], None), "dimensions may not be zero"),
159            ("no height", image((16, 0), 2.0, vec![], vec![], None), "dimensions may not be zero"),
160            ("no pixel ratio", image((16, 16), 0.0, vec![], vec![], None), "pixelRatio may not be <= 0"),
161            ("a stretch before the left", image((16, 16), 1.0, vec![(-1.0, 3.0)], vec![], None), stretch_x),
162            ("overlapping stretches", image((16, 16), 1.0, vec![(0.0, 3.0), (2.0, 4.0)], vec![], None), stretch_x),
163            ("a stretch past the bottom", image((16, 16), 1.0, vec![], vec![(14.0, 20.0)], None), stretch_y),
164            ("unsorted stretches", image((16, 16), 1.0, vec![], vec![(4.0, 8.0), (2.0, 3.0)], None), stretch_y),
165            (
166                "content past the corner",
167                image((16, 16), 1.0, vec![], vec![], Some(content(0.0, 0.0, 24.0, 28.0))),
168                "content area is invalid",
169            ),
170            (
171                "inverted content",
172                image((16, 16), 1.0, vec![], vec![], Some(content(14.0, 14.0, 12.0, 10.0))),
173                "content area is invalid",
174            ),
175            (
176                "content before the corner",
177                image((16, 16), 1.0, vec![], vec![], Some(content(-2.0, -8.0, 12.0, 10.0))),
178                "content area is invalid",
179            ),
180        ] {
181            assert_eq!(Some(error.to_owned()), result.err(), "{name}");
182        }
183    }
184
185    #[test]
186    fn a_valid_image_keeps_its_stretches_and_content() {
187        let image =
188            image((20, 12), 1.5, vec![(2.0, 14.0)], vec![(0.0, 4.0), (8.0, 12.0)], Some(content(2.0, 2.0, 14.0, 10.0)))
189                .unwrap();
190        assert_eq!((Size::new(20, 12), 1.5), (image.image.size, image.pixel_ratio));
191        assert_eq!(vec![(2.0, 14.0)], image.stretch_x);
192        assert_eq!(vec![(0.0, 4.0), (8.0, 12.0)], image.stretch_y);
193        assert_eq!(Some(content(2.0, 2.0, 14.0, 10.0)), image.content);
194    }
195}