use crate::common::geom::Rect;
use base64::Engine;
use hayro::vello_cpu::color::palette::css::{TRANSPARENT, WHITE};
use hayro::vello_cpu::{Pixmap, RasterizerSettings, RenderContext, Resources, TargetInit};
use hayro::{RenderCache, RenderSettings, render_into};
use hayro_interpret::InterpreterSettings;
use hayro_interpret::util::TransformExt;
use hayro_syntax::Pdf;
use kurbo::Affine;
use std::collections::{HashMap, HashSet};
const MAX_BITMAP_SIDE_PX: f32 = 6000.0;
const SVG_BACKGROUND: [u8; 4] = [255, 255, 255, 255];
const PNG_DATA_URI: &str = "data:image/png;base64,";
const JPEG_DATA_URI: &str = "data:image/jpeg;base64,";
const MIN_RECOMPRESS_LEN: usize = 200_000;
const MAX_IMAGE_SIDE_PX: u32 = 2600;
const JPEG_QUALITY: u8 = 88;
const PHOTO_MIN_PNG_BYTES: usize = 64_000;
const PHOTO_MIN_COLOURS: usize = 4096;
const GLYPH_USE_PREFIX: &str = "<use xlink:href=\"#";
const TRANSFORM_ATTR: &str = "transform=\"";
const GLYPH_DEF_PREFIX: &str = "<path id=\"";
const BLANK_GLYPH_SUFFIX: &str = " d=\"\"/>";
const PIXELATED_STYLE: &str = " style=\"image-rendering: pixelated\"";
const PIXELATED_MIN_PIXEL_PT: f64 = 1.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PngCompression {
Fast,
#[default]
Balanced,
High,
}
impl PngCompression {
fn level(self) -> png::Compression {
match self {
Self::Fast => png::Compression::Fast,
Self::Balanced => png::Compression::Balanced,
Self::High => png::Compression::High,
}
}
}
fn encode_png(pixmap: Pixmap, compression: PngCompression) -> Option<Vec<u8>> {
if compression == PngCompression::Balanced {
return pixmap.into_png().ok();
}
let (width, height) = (u32::from(pixmap.width()), u32::from(pixmap.height()));
let (color, pixels) = match pixmap.try_take_rgb8(hayro::vello_cpu::peniko::ImageAlphaType::Alpha) {
hayro::vello_cpu::Pixels::Rgb8(pixels) => (png::ColorType::Rgb, pixels),
hayro::vello_cpu::Pixels::Rgba8(pixels) => (png::ColorType::Rgba, pixels),
};
let mut data = Vec::new();
let mut encoder = png::Encoder::new(&mut data, width, height);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_compression(compression.level());
let mut writer = encoder.write_header().ok()?;
writer.write_image_data(&pixels).ok()?;
writer.finish().ok()?;
Some(data)
}
pub struct PageRenderer<'a> {
pdf: &'a Pdf,
cache: RenderCache<'a>,
svg_cache: hayro_svg::RenderCache<'a>,
settings: InterpreterSettings,
png: PngCompression,
}
impl<'a> PageRenderer<'a> {
pub fn new(pdf: &'a Pdf) -> Self {
Self {
pdf,
cache: RenderCache::new(),
svg_cache: hayro_svg::RenderCache::new(),
settings: InterpreterSettings::default(),
png: PngCompression::default(),
}
}
#[must_use]
pub fn with_png_compression(mut self, compression: PngCompression) -> Self {
self.png = compression;
self
}
pub fn region_png(&self, page: usize, rect: Rect, scale: f32, transparent: bool) -> Option<(Vec<u8>, u32, u32)> {
let pixmap = self.region_pixmap(page, rect, scale, transparent)?;
let (width, height) = (u32::from(pixmap.width()), u32::from(pixmap.height()));
let png = encode_png(pixmap, self.png)?;
Some((png, width, height))
}
pub fn region_picture(&self, page: usize, rect: Rect, scale: f32, transparent: bool) -> Option<(Vec<u8>, bool)> {
let pixmap = self.region_pixmap(page, rect, scale, transparent)?;
let (width, height) = (u32::from(pixmap.width()), u32::from(pixmap.height()));
let rgba = (!transparent).then(|| pixmap.data_as_u8_slice().to_vec());
let png = encode_png(pixmap, self.png)?;
if let Some(rgba) = rgba
&& png.len() >= PHOTO_MIN_PNG_BYTES
&& many_colours(&rgba, PHOTO_MIN_COLOURS)
&& let Some(jpeg) = encode_jpeg(&rgba, width, height)
&& jpeg.len() * 2 < png.len()
{
return Some((jpeg, true));
}
Some((png, false))
}
fn region_pixmap(&self, page: usize, rect: Rect, scale: f32, transparent: bool) -> Option<Pixmap> {
let page = self.pdf.pages().get(page)?;
let (scale, width, height) = region_bitmap(rect, scale);
let (width_px, height_px) = (width as u16, height as u16);
let mut ctx = RenderContext::new(width_px, height_px);
let transform = Affine::scale(scale as f64)
* Affine::translate((-rect.x0 as f64, -rect.y0 as f64))
* page.initial_transform(true).to_kurbo();
render_into(
page,
&self.cache,
&self.settings,
&RenderSettings::default(),
&mut ctx,
transform,
);
ctx.flush();
let mut pixmap = Pixmap::new(width_px, height_px);
ctx.render_with(
&mut pixmap,
&mut Resources::default(),
RasterizerSettings {
target_init: TargetInit::Clear(if transparent { TRANSPARENT } else { WHITE }),
..Default::default()
},
);
Some(pixmap)
}
pub fn page_png(&self, page: usize, scale: f32) -> Option<(Vec<u8>, u32, u32)> {
let pdf_page = self.pdf.pages().get(page)?;
let (width, height) = pdf_page.render_dimensions();
self.region_png(page, Rect::new(0.0, 0.0, width, height), scale, false)
}
pub fn page_svg_without_text(&self, page: usize, remove: &dyn Fn(f32, f32) -> bool) -> Option<String> {
self.page_svg_without_glyphs(page, remove, false)
}
pub fn page_svg_without_all_text(&self, page: usize, remove: &dyn Fn(f32, f32) -> bool) -> Option<String> {
self.page_svg_without_glyphs(page, remove, true)
}
fn page_svg_without_glyphs(&self, page: usize, remove: &dyn Fn(f32, f32) -> bool, type3: bool) -> Option<String> {
let svg = self.page_svg(page)?;
let group_origins = if type3 {
group_glyph_origins(&svg)
} else {
HashMap::new()
};
let blank: HashSet<&str> = svg
.lines()
.filter(|line| line.trim_end().ends_with(BLANK_GLYPH_SUFFIX))
.filter_map(glyph_def)
.collect();
let mut dropped_lines = Vec::new();
let mut referenced: HashSet<&str> = HashSet::new();
for line in svg.lines() {
if let Some(&(x, y)) = group_use(line).and_then(|id| group_origins.get(id))
&& remove(x, y)
{
dropped_lines.push(true);
continue;
}
match glyph_use(line) {
Some((id, x, y)) if blank.contains(id) || remove(x, y) => dropped_lines.push(true),
Some((id, _, _)) => {
referenced.insert(id);
dropped_lines.push(false);
}
None => dropped_lines.push(false),
}
}
let mut out = String::with_capacity(svg.len() / 2);
for (line, dropped) in svg.lines().zip(dropped_lines) {
if dropped || glyph_def(line).is_some_and(|id| !referenced.contains(id)) {
continue;
}
out.push_str(line.trim_start());
out.push('\n');
}
Some(out)
}
pub fn page_svg(&self, page: usize) -> Option<String> {
let pdf_page = self.pdf.pages().get(page)?;
let svg = hayro_svg::convert(
pdf_page,
&self.svg_cache,
&self.settings,
&hayro_svg::SvgRenderSettings {
bg_color: SVG_BACKGROUND,
},
);
Some(smooth_fine_images(compact_images(svg)))
}
}
pub(crate) fn svg_fonts() -> std::sync::Arc<resvg::usvg::fontdb::Database> {
static FONTS: std::sync::OnceLock<std::sync::Arc<resvg::usvg::fontdb::Database>> = std::sync::OnceLock::new();
FONTS
.get_or_init(|| {
let mut fonts = resvg::usvg::fontdb::Database::new();
fonts.load_system_fonts();
if let Some(dirs) = std::env::var_os("KAKEMONO_FONT_DIRS") {
for dir in std::env::split_paths(&dirs) {
fonts.load_fonts_dir(dir);
}
}
let ids: Vec<_> = fonts.faces().map(|face| face.id).collect();
for id in ids {
unsafe {
fonts.make_shared_face_data(id);
}
}
fonts.set_serif_family("Liberation Serif");
fonts.set_sans_serif_family("Liberation Sans");
fonts.set_monospace_family("Liberation Mono");
std::sync::Arc::new(fonts)
})
.clone()
}
pub fn svg_to_png(svg: &str, scale: f32) -> Option<Vec<u8>> {
svg_to_png_in(svg, scale, None).ok()
}
pub fn svg_to_png_in(svg: &str, scale: f32, resources: Option<&std::path::Path>) -> Result<Vec<u8>, String> {
use resvg::{tiny_skia, usvg};
let options = usvg::Options {
fontdb: svg_fonts(),
resources_dir: resources.map(std::path::Path::to_path_buf),
..Default::default()
};
let tree = usvg::Tree::from_str(svg, &options).map_err(|err| err.to_string())?;
let size = tree
.size()
.to_int_size()
.scale_by(scale)
.ok_or("the scaled size is empty")?;
let mut pixmap = tiny_skia::Pixmap::new(size.width(), size.height()).ok_or("the picture is too large")?;
pixmap.fill(tiny_skia::Color::WHITE);
resvg::render(
&tree,
tiny_skia::Transform::from_scale(scale, scale),
&mut pixmap.as_mut(),
);
pixmap.encode_png().map_err(|err| err.to_string())
}
fn smooth_fine_images(svg: String) -> String {
if !svg.contains(PIXELATED_STYLE) {
return svg;
}
let mut out = String::with_capacity(svg.len());
for line in svg.split_inclusive('\n') {
let pixel_pt = line.contains(PIXELATED_STYLE).then(|| image_pixel_pt(line)).flatten();
match pixel_pt {
Some(size) if size < PIXELATED_MIN_PIXEL_PT => out.push_str(&line.replacen(PIXELATED_STYLE, "", 1)),
_ => out.push_str(line),
}
}
out
}
fn image_pixel_pt(line: &str) -> Option<f64> {
let rest = &line[line.find("<image ")?..];
let matrix = &rest[rest.find("matrix(")? + "matrix(".len()..];
let values: Vec<f64> = matrix[..matrix.find(')')?]
.split([' ', ','])
.filter(|value| !value.is_empty())
.map(str::parse)
.collect::<Result<_, _>>()
.ok()?;
let [x_scale, y_skew, x_skew, y_scale, ..] = values.as_slice() else {
return None;
};
Some((x_scale * y_scale - y_skew * x_skew).abs().sqrt())
}
fn glyph_use(line: &str) -> Option<(&str, f32, f32)> {
let trimmed = line.trim_start();
let rest = trimmed.strip_prefix(GLYPH_USE_PREFIX)?;
let id = &rest[..rest.find('"')?];
let transform = &rest[rest.find(TRANSFORM_ATTR)? + TRANSFORM_ATTR.len()..];
let transform = &transform[..transform.find('"')?];
let inner = transform
.strip_prefix("matrix(")
.or_else(|| transform.strip_prefix("translate("))?
.strip_suffix(')')?;
let nums: Vec<f32> = inner
.split([' ', ','])
.filter(|part| !part.is_empty())
.filter_map(|part| part.parse().ok())
.collect();
let n = nums.len();
(n >= 2).then(|| (id, nums[n - 2], nums[n - 1]))
}
fn group_glyph_origins(svg: &str) -> HashMap<&str, (f32, f32)> {
let mut origins = HashMap::new();
let mut lines = svg.lines().peekable();
while let Some(line) = lines.next() {
let Some(id) = line
.trim_start()
.strip_prefix("<g id=\"")
.and_then(|rest| rest.strip_suffix("\">"))
else {
continue;
};
let Some(child) = lines.peek().map(|child| child.trim_start()) else {
continue;
};
if !child.starts_with("<path ") {
continue;
}
if let Some(start) = child.find("transform=\"matrix(") {
let inner = &child[start + "transform=\"matrix(".len()..];
let nums: Vec<f32> = inner[..inner.find(')').unwrap_or(0)]
.split([' ', ','])
.filter_map(|part| part.parse().ok())
.collect();
if nums.len() == 6 {
origins.insert(id, (nums[4], nums[5]));
}
}
}
origins
}
fn group_use(line: &str) -> Option<&str> {
line.trim().strip_prefix("<use xlink:href=\"#")?.strip_suffix("\"/>")
}
fn glyph_def(line: &str) -> Option<&str> {
let rest = line.trim_start().strip_prefix(GLYPH_DEF_PREFIX)?;
let id = &rest[..rest.find('"')?];
(id.starts_with('g') && id[1..].chars().all(|ch| ch.is_ascii_digit()) && id.len() > 1).then_some(id)
}
fn compact_images(svg: String) -> String {
if !svg.contains(PNG_DATA_URI) {
return svg;
}
let engine = base64::engine::general_purpose::STANDARD;
let mut out = String::with_capacity(svg.len());
let mut rest = svg.as_str();
while let Some(pos) = rest.find(PNG_DATA_URI) {
let start = pos + PNG_DATA_URI.len();
let len = rest[start..].find('"').unwrap_or(rest.len() - start);
let payload = &rest[start..start + len];
let replacement = recompress_png(&engine, payload);
out.push_str(&rest[..pos]);
match replacement {
Some(jpeg) => {
out.push_str(JPEG_DATA_URI);
out.push_str(&engine.encode(jpeg));
}
None => {
out.push_str(PNG_DATA_URI);
out.push_str(payload);
}
}
rest = &rest[start + len..];
}
out.push_str(rest);
out
}
fn recompress_png(engine: &base64::engine::GeneralPurpose, payload: &str) -> Option<Vec<u8>> {
let len = payload.len();
(len >= MIN_RECOMPRESS_LEN)
.then(|| engine.decode(payload).ok())
.flatten()
.and_then(|png| image::load_from_memory_with_format(&png, image::ImageFormat::Png).ok())
.and_then(|img| {
if img.color().has_alpha() && img.to_rgba8().pixels().any(|pixel| pixel.0[3] != 255) {
return None;
}
let img = if img.width().max(img.height()) > MAX_IMAGE_SIDE_PX {
img.resize(
MAX_IMAGE_SIDE_PX,
MAX_IMAGE_SIDE_PX,
image::imageops::FilterType::Triangle,
)
} else {
img
};
let mut jpeg = Vec::new();
let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, JPEG_QUALITY);
img.to_rgb8().write_with_encoder(encoder).ok()?;
Some(jpeg)
})
.filter(|jpeg| jpeg.len() * 4 / 3 < len)
}
fn many_colours(rgba: &[u8], min: usize) -> bool {
let mut seen = vec![0u64; (1 << 24) / 64];
let mut count = 0usize;
for pixel in rgba.as_chunks::<4>().0 {
let colour = (usize::from(pixel[0]) << 16) | (usize::from(pixel[1]) << 8) | usize::from(pixel[2]);
let (word, bit) = (colour / 64, 1u64 << (colour % 64));
if seen[word] & bit == 0 {
seen[word] |= bit;
count += 1;
if count >= min {
return true;
}
}
}
false
}
fn encode_jpeg(rgba: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
let rgb: Vec<u8> = rgba
.as_chunks::<4>()
.0
.iter()
.flat_map(|pixel| [pixel[0], pixel[1], pixel[2]])
.collect();
let mut jpeg = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, JPEG_QUALITY)
.encode(&rgb, width, height, image::ExtendedColorType::Rgb8)
.ok()?;
Some(jpeg)
}
pub fn region_bitmap(rect: Rect, scale: f32) -> (f32, u32, u32) {
let scale = scale
.min(MAX_BITMAP_SIDE_PX / rect.width().max(1.0))
.min(MAX_BITMAP_SIDE_PX / rect.height().max(1.0));
let width = (rect.width() * scale).ceil().max(1.0) as u32;
let height = (rect.height() * scale).ceil().max(1.0) as u32;
(scale, width, height)
}
#[cfg(test)]
mod smoothing_tests {
use super::smooth_fine_images;
#[test]
fn fine_pictures_are_smoothed_and_coarse_ones_stay_sharp() {
let line = |scale: f64| {
format!(
"<image transform=\"matrix({scale} 0 0 {scale} 10 20)\" xlink:href=\"data:image/png;base64,AAAA\" \
width=\"484\" height=\"209\" preserveAspectRatio=\"none\" style=\"image-rendering: pixelated\"/>\n"
)
};
assert!(!smooth_fine_images(line(0.588843)).contains("pixelated"));
assert!(smooth_fine_images(line(1.8)).contains("pixelated"));
}
}