use std::sync::Arc;
use mln_style::bitmap::PremultipliedImage;
use mln_style::error::Error;
use mln_style::geometry::Point;
use mln_style::image::{ImageContent, ImageStretches, StyleImage, TextFit};
use mln_style::size::Size;
use mln_style::string::to_string_double;
use serde_json::{Map, Value as JSValue};
use crate::exec::pool::Respond;
use crate::image::decoder;
use crate::log_target;
use crate::storage::Data;
#[derive(Default)]
pub(crate) struct SpriteImageSpec {
pub(crate) x: i32,
pub(crate) y: i32,
pub(crate) width: i32,
pub(crate) height: i32,
pub(crate) ratio: f64,
pub(crate) sdf: bool,
pub(crate) stretch_x: ImageStretches,
pub(crate) stretch_y: ImageStretches,
pub(crate) content: Option<ImageContent>,
pub(crate) text_fit_width: Option<TextFit>,
pub(crate) text_fit_height: Option<TextFit>,
}
#[must_use]
pub(crate) fn create_style_image(id: &str, image: &PremultipliedImage, spec: SpriteImageSpec) -> Option<StyleImage> {
if spec.width <= 0
|| spec.height <= 0
|| spec.width > 1024
|| spec.height > 1024
|| spec.ratio <= 0.0
|| spec.ratio > 10.0
|| spec.x < 0
|| spec.y < 0
|| i64::from(spec.x) + i64::from(spec.width) > i64::from(image.size.width)
|| i64::from(spec.y) + i64::from(spec.height) > i64::from(image.size.height)
{
tracing::error!(
target: log_target::SPRITE,
width = spec.width,
height = spec.height,
x = spec.x,
y = spec.y,
image_width = image.size.width,
image_height = image.size.height,
ratio = %to_string_double(spec.ratio),
"Can't create an image with invalid metrics"
);
return None;
}
let size = Size::new(spec.width as u32, spec.height as u32);
let mut dst_image = PremultipliedImage::new(size);
if let Err(err) = PremultipliedImage::copy(
image,
&mut dst_image,
Point::new(spec.x as u32, spec.y as u32),
Point::new(0, 0),
size,
) {
tracing::error!(target: log_target::SPRITE, error = %err, "Can't copy sprite image");
return None;
}
match StyleImage::new(
id.to_owned(),
dst_image,
spec.ratio as f32,
spec.sdf,
spec.stretch_x,
spec.stretch_y,
spec.content,
spec.text_fit_width,
spec.text_fit_height,
) {
Ok(image) => Some(image),
Err(ex) => {
tracing::error!(target: log_target::SPRITE, error = %ex, "Can't create an image with invalid metadata");
None
}
}
}
fn warn(name: &str, message: std::fmt::Arguments<'_>) {
tracing::warn!(target: log_target::SPRITE, name, error = %message, "Invalid sprite image");
}
fn member<'a, T>(
entry: &'a Map<String, JSValue>,
name: &str,
property: &str,
must: &str,
read: impl FnOnce(&'a JSValue) -> Option<T>,
) -> Option<T> {
let value = read(entry.get(property)?);
if value.is_none() {
warn(name, format_args!("value of '{property}' must be {must}"));
}
value
}
fn integer(entry: &Map<String, JSValue>, name: &str, property: &str) -> u16 {
member(entry, name, property, "an integer between 0 and 65535", |value| {
let value = value.as_u64()?;
u16::try_from(value).ok()
})
.unwrap_or(0)
}
fn stretches(entry: &Map<String, JSValue>, name: &str, property: &str) -> ImageStretches {
let Some(pairs) = member(entry, name, property, "an array", JSValue::as_array) else {
return ImageStretches::new();
};
pairs
.iter()
.filter_map(|pair| {
let stretch = match pair.as_array().map(Vec::as_slice) {
Some([start, end]) => start.as_f64().zip(end.as_f64()),
_ => None,
};
if stretch.is_none() {
warn(name, format_args!("members of '{property}' must be an array of two numbers"));
}
stretch.map(|(start, end)| (start as f32, end as f32))
})
.collect()
}
fn content(entry: &Map<String, JSValue>, name: &str, property: &str) -> Option<ImageContent> {
member(entry, name, property, "an array of four numbers", |value| {
let [left, top, right, bottom] = value.as_array()?.as_slice() else { return None };
let side = |value: &JSValue| value.as_f64().map(|value| value as f32);
Some(ImageContent { left: side(left)?, top: side(top)?, right: side(right)?, bottom: side(bottom)? })
})
}
fn text_fit(entry: &Map<String, JSValue>, name: &str, property: &str) -> Option<TextFit> {
let value = member(entry, name, property, "a string", JSValue::as_str)?;
let text_fit = match value {
"stretchOrShrink" => Some(TextFit::StretchOrShrink),
"stretchOnly" => Some(TextFit::StretchOnly),
"proportional" => Some(TextFit::Proportional),
_ => None,
};
if text_fit.is_none() {
warn(name, format_args!("value of '{property}' is an invalid value '{value}'"));
}
text_fit
}
#[expect(clippy::needless_pass_by_value, reason = "a job owns its inputs, as one sent to another thread does")]
pub fn load_sprite(id: String, image: Data, json: Data, respond: Respond<Result<Vec<Arc<StyleImage>>, Error>>) {
decoder::decode(&image, move |raster| respond(raster.and_then(|raster| parse_sprite(&id, &raster, &json))));
}
pub fn parse_sprite(id: &str, image: &PremultipliedImage, json: &[u8]) -> Result<Vec<Arc<StyleImage>>, Error> {
let doc: JSValue = serde_json::from_slice(json).map_err(|e| Error::failed(format!("Failed to parse JSON: {e}")))?;
let JSValue::Object(entries) = doc else {
return Err(Error::failed("Sprite JSON root must be an object"));
};
let mut images = Vec::with_capacity(entries.len());
for (name, value) in &entries {
let Some(entry) = value.as_object() else { continue };
let complete_name = if id == "default" { name.clone() } else { format!("{id}:{name}") };
let spec = SpriteImageSpec {
x: i32::from(integer(entry, name, "x")),
y: i32::from(integer(entry, name, "y")),
width: i32::from(integer(entry, name, "width")),
height: i32::from(integer(entry, name, "height")),
ratio: member(entry, name, "pixelRatio", "a number", JSValue::as_f64).unwrap_or(1.0),
sdf: member(entry, name, "sdf", "a boolean", JSValue::as_bool).unwrap_or(false),
stretch_x: stretches(entry, name, "stretchX"),
stretch_y: stretches(entry, name, "stretchY"),
content: content(entry, name, "content"),
text_fit_width: text_fit(entry, name, "textFitWidth"),
text_fit_height: text_fit(entry, name, "textFitHeight"),
};
let image = create_style_image(&complete_name, image, spec);
if let Some(image) = image {
images.push(Arc::new(image));
}
}
Ok(images)
}