use std::collections::HashSet;
use base64::Engine;
use super::{decode_image_with_format_limited, memoized, Conversion, Cursor};
use crate::renderer::svg_fragment::{
decode_base64_data_url, find_svg_attr_value, try_parse_single_image_data_url,
};
pub(super) fn adjusted_wmf_picture_svg(
data: &[u8],
brightness: i8,
contrast: i8,
grayscale: bool,
) -> Option<Vec<u8>> {
let brightness = brightness.clamp(-100, 100);
let contrast = contrast.clamp(-100, 100);
memoized(
Conversion::WmfPictureTone {
brightness,
contrast,
grayscale,
},
data,
|| {
let converted = crate::renderer::svg::convert_wmf_to_svg(data)?;
let svg = std::str::from_utf8(&converted).ok()?.trim();
let body = svg.strip_prefix("<svg ")?;
let root_end = body.find('>')?;
let image = body[root_end + 1..].strip_suffix("</svg>")?.trim();
if image.matches("href=\"").count() != 1 {
return None;
}
let normalized_image = if let Some(start) = image.strip_suffix("</image>") {
format!("{}/>", start.trim_end().strip_suffix('>')?)
} else {
image.to_owned()
};
let url = try_parse_single_image_data_url(&normalized_image)?;
let (mime, png) = decode_base64_data_url(url)?;
if mime != "image/png" {
return None;
}
let mut pixels =
decode_image_with_format_limited(&png, image::ImageFormat::Png)?.to_rgba8();
if pixels.pixels().any(|pixel| pixel[3] != 255) {
return None;
}
adjust_pixels(&mut pixels, brightness, contrast, grayscale);
let mut adjusted = Vec::new();
pixels
.write_to(&mut Cursor::new(&mut adjusted), image::ImageFormat::Png)
.ok()?;
let encoded = base64::engine::general_purpose::STANDARD.encode(adjusted);
let root = &svg[..svg.find('>')? + 1];
let adjusted = svg.replacen(url, &format!("data:image/png;base64,{encoded}"), 1);
let adjusted = if find_svg_attr_value(root, "width").is_none()
&& find_svg_attr_value(root, "height").is_none()
{
let view_box: Vec<i32> = find_svg_attr_value(root, "viewBox")?
.split_ascii_whitespace()
.map(str::parse)
.collect::<Result<_, _>>()
.ok()?;
let [_, _, width, height]: [i32; 4] = view_box.try_into().ok()?;
if width <= 0 || height <= 0 {
return None;
}
adjusted.replacen(
"<svg ",
&format!("<svg width=\"{width}\" height=\"{height}\" "),
1,
)
} else {
adjusted
};
Some(adjusted.into_bytes())
},
)
}
pub(crate) fn adjust_pixels(
pixels: &mut image::RgbaImage,
brightness: i8,
contrast: i8,
grayscale: bool,
) {
let brightness = brightness.clamp(-100, 100);
let contrast = contrast.clamp(-100, 100);
let mut colors = HashSet::with_capacity(257);
for pixel in pixels.pixels_mut() {
if pixel[3] == 0 {
pixel.0[..3].fill(255);
continue;
}
if grayscale {
let gray =
(299 * u32::from(pixel[0]) + 587 * u32::from(pixel[1]) + 114 * u32::from(pixel[2]))
/ 1000;
pixel.0[..3].fill(gray as u8);
}
for channel in &mut pixel.0[..3] {
*channel = adjusted_wmf_channel(*channel, brightness, contrast);
}
if colors.len() <= 256 {
colors.insert([pixel[0], pixel[1], pixel[2]]);
}
}
if colors.len() > 256 {
for pixel in pixels.pixels_mut().filter(|pixel| pixel[3] != 0) {
for channel in &mut pixel.0[..3] {
*channel = rgb555_dither_mean(*channel);
}
}
}
}
fn adjusted_wmf_channel(channel: u8, brightness: i8, contrast: i8) -> u8 {
if contrast == -100 || contrast == 100 {
return super::picture_adjustments::adjusted_channel(channel, brightness, contrast);
}
let c = i64::from(contrast);
let gain = if c >= 0 { 10000 / (100 - c) } else { 100 + c };
let numerator = 200 * gain * i64::from(channel)
+ 25600 * (100 - gain)
+ 255 * i64::from(brightness) * (100 + gain);
(numerator / 20000).clamp(0, 255) as u8
}
fn rgb555_dither_mean(channel: u8) -> u8 {
let low = u16::from(channel >> 3);
let high = (low + 1).min(31);
let remainder = u16::from(channel & 7);
let expand = |value: u16| (value << 3) | (value >> 2);
((expand(low) * (8 - remainder) + expand(high) * remainder + 4) / 8) as u8
}