use super::device_context::BitmapPattern;
use crate::emf::parser::records::DibPatternBrush;
pub(super) fn decode(brush: &DibPatternBrush) -> Option<BitmapPattern> {
if brush.usage != 0 || brush.bmi.len() < 12 {
return None;
}
let header_size = u32::from_le_bytes(brush.bmi[..4].try_into().ok()?);
let (width, height) = if header_size == 12 {
(
u32::from(u16::from_le_bytes(brush.bmi[4..6].try_into().ok()?)),
u32::from(u16::from_le_bytes(brush.bmi[6..8].try_into().ok()?)),
)
} else if header_size >= 40 && brush.bmi.len() >= 40 {
let width = i32::from_le_bytes(brush.bmi[4..8].try_into().ok()?);
let height = i32::from_le_bytes(brush.bmi[8..12].try_into().ok()?);
(u32::try_from(width).ok()?, height.unsigned_abs())
} else {
return None;
};
if width == 0 || height == 0 {
return None;
}
let data_url = super::player::dib_to_bmp_data_url(&brush.bmi, &brush.bits);
data_url
.starts_with("data:image/png;")
.then_some(BitmapPattern {
width,
height,
data_url,
})
}
pub(super) fn definition(
pattern: &BitmapPattern,
id: &str,
device_to_logical: super::device_stroke::Matrix,
) -> String {
let [a, b, c, d, e, f] = device_to_logical;
let width = pattern.width;
let height = pattern.height;
format!(
"<defs><pattern id=\"{id}\" patternUnits=\"userSpaceOnUse\" width=\"{width}\" height=\"{height}\" patternTransform=\"matrix({a} {b} {c} {d} {e} {f})\"><image width=\"{width}\" height=\"{height}\" preserveAspectRatio=\"none\" href=\"{}\"/></pattern></defs>",
pattern.data_url,
)
}