use crate::bitmap::PremultipliedImage;
use crate::error::Error;
use crate::size::Size;
pub type ImageStretch = (f32, f32);
pub type ImageStretches = Vec<ImageStretch>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, mln_wire::Wire)]
pub enum TextFit {
StretchOrShrink,
StretchOnly,
Proportional,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
pub struct ImageContent {
pub left: f32,
pub top: f32,
pub right: f32,
pub bottom: f32,
}
#[derive(Clone, Debug, mln_wire::Wire)]
pub struct StyleImage {
pub id: String,
pub image: PremultipliedImage,
pub pixel_ratio: f32,
pub sdf: bool,
pub stretch_x: ImageStretches,
pub stretch_y: ImageStretches,
pub content: Option<ImageContent>,
pub text_fit_width: Option<TextFit>,
pub text_fit_height: Option<TextFit>,
pub keep_unused: bool,
}
fn validate_stretch(stretches: &ImageStretches, size: f32) -> bool {
if stretches.is_empty() {
return true;
}
let mut last = 0.0f32;
for part in stretches {
if part.0 < last || part.1 < part.0 || size < part.1 {
return false;
}
last = part.1;
}
true
}
fn validate_content(content: &ImageContent, size: Size) -> bool {
let (width, height) = (size.width as f32, size.height as f32);
if content.left < 0.0 || width < content.left {
return false;
}
if content.top < 0.0 || height < content.top {
return false;
}
if content.right < 0.0 || width < content.right {
return false;
}
if content.bottom < 0.0 || height < content.bottom {
return false;
}
if content.right < content.left {
return false;
}
if content.bottom < content.top {
return false;
}
true
}
impl StyleImage {
#[expect(clippy::too_many_arguments, reason = "each argument is a field of the image")]
pub fn new(
id: String,
image: PremultipliedImage,
pixel_ratio: f32,
sdf: bool,
stretch_x: ImageStretches,
stretch_y: ImageStretches,
content: Option<ImageContent>,
text_fit_width: Option<TextFit>,
text_fit_height: Option<TextFit>,
) -> Result<Self, Error> {
if !image.valid() {
return Err(Error::invalid_argument("dimensions may not be zero"));
} else if pixel_ratio <= 0.0 {
return Err(Error::invalid_argument("pixelRatio may not be <= 0"));
} else if !validate_stretch(&stretch_x, image.size.width as f32) {
return Err(Error::invalid_argument("stretchX is out of bounds or overlapping"));
} else if !validate_stretch(&stretch_y, image.size.height as f32) {
return Err(Error::invalid_argument("stretchY is out of bounds or overlapping"));
} else if content.as_ref().is_some_and(|content| !validate_content(content, image.size)) {
return Err(Error::invalid_argument("content area is invalid"));
}
Ok(StyleImage {
id,
image,
pixel_ratio,
sdf,
stretch_x,
stretch_y,
content,
text_fit_width,
text_fit_height,
keep_unused: false,
})
}
}