use std::fmt::Write as _;
use hayro_interpret::font::Glyph as PdfGlyph;
use hayro_interpret::font::GlyphRun;
use hayro_interpret::kurbo::{Affine, BezPath, PathEl, Rect, Shape};
use hayro_interpret::{
interpret_page, BlendMode, ClipPath, Context, Device, DrawMode, DrawProps, FillRule, Image,
ImageDrawProps, InterpreterCache, InterpreterSettings, Paint, SoftMask,
};
use crate::read::Refusal;
struct Draw {
region: Rect,
out: String,
}
fn colour(paint: &Paint) -> (String, f32) {
match paint {
Paint::Color(c) => {
let [r, g, b, a] = c.to_rgba().to_rgba8();
(format!("#{r:02x}{g:02x}{b:02x}"), f32::from(a) / 255.0)
}
Paint::Pattern(_) => ("#000000".into(), 1.0),
}
}
fn d_of(p: &BezPath) -> String {
let mut d = String::new();
for el in p.elements() {
let _ = match *el {
PathEl::MoveTo(a) => write!(d, "M{:.2} {:.2}", a.x, a.y),
PathEl::LineTo(a) => write!(d, "L{:.2} {:.2}", a.x, a.y),
PathEl::QuadTo(a, b) => write!(d, "Q{:.2} {:.2} {:.2} {:.2}", a.x, a.y, b.x, b.y),
PathEl::CurveTo(a, b, c) => write!(
d,
"C{:.2} {:.2} {:.2} {:.2} {:.2} {:.2}",
a.x, a.y, b.x, b.y, c.x, c.y
),
PathEl::ClosePath => write!(d, "Z"),
};
}
d
}
impl Draw {
fn path(&mut self, p: &BezPath, paint: &Paint, mode: &DrawMode, scale: f64) {
let b = p.bounding_box();
if b.x1 < self.region.x0 - 2.0
|| b.x0 > self.region.x1 + 2.0
|| b.y1 < self.region.y0 - 2.0
|| b.y0 > self.region.y1 + 2.0
{
return;
}
let (c, a) = colour(paint);
let opacity = match a < 1.0 {
true => format!(" opacity=\"{a:.2}\""),
false => String::new(),
};
let d = d_of(p);
let rule = |r: &FillRule| match r {
FillRule::NonZero => "",
FillRule::EvenOdd => " fill-rule=\"evenodd\"",
};
let stroke = |w: f32| {
format!(
" stroke=\"{c}\" stroke-width=\"{:.2}\"",
(w as f64 * scale).max(0.1)
)
};
let _ = match mode {
DrawMode::Fill(r) => writeln!(
self.out,
"<path d=\"{d}\" fill=\"{c}\"{}{opacity}/>",
rule(r)
),
DrawMode::Stroke(sp) => writeln!(
self.out,
"<path d=\"{d}\" fill=\"none\"{}{opacity}/>",
stroke(sp.line_width)
),
DrawMode::FillAndStroke(r, sp) => writeln!(
self.out,
"<path d=\"{d}\" fill=\"{c}\"{}{}{opacity}/>",
rule(r),
stroke(sp.line_width)
),
DrawMode::Invisible => Ok(()),
};
}
}
fn scale_of(t: &Affine) -> f64 {
let c = t.as_coeffs();
(c[0] * c[3] - c[1] * c[2]).abs().sqrt()
}
impl<'a> Device<'a> for Draw {
fn draw_path(&mut self, path: &BezPath, props: DrawProps<'a>, mode: &DrawMode) {
let p = props.transform * path.clone();
self.path(&p, &props.paint, mode, scale_of(&props.transform));
}
fn push_clip_path(&mut self, _: &ClipPath) {}
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
fn draw_glyph_run(&mut self, run: &GlyphRun<'_, 'a>, props: DrawProps<'a>, mode: &DrawMode) {
for g in run.glyphs() {
match &**g {
PdfGlyph::Outline(og) => {
let t = props.transform * g.transform();
let p = t * og.outline();
self.path(&p, &props.paint, mode, scale_of(&props.transform));
}
PdfGlyph::Type3(t3) => {
t3.interpret(self, props.transform, g.transform(), &props.paint);
}
}
}
}
fn draw_image(&mut self, _: Image<'a, '_>, _: ImageDrawProps<'a>) {}
fn pop_clip(&mut self) {}
fn pop_transparency_group(&mut self) {}
}
pub fn page_svg(pdf: &[u8], page: usize, region: [f64; 4]) -> Result<String, Refusal> {
let refuse = |why: String| Refusal { system: None, why };
let doc = hayro_syntax::Pdf::new(pdf.to_vec())
.map_err(|e| refuse(format!("not a PDF it can open ({e:?})")))?;
let pages = doc.pages();
let Some(pg) = pages.get(page) else {
return Err(refuse(format!("it has no page {}", page + 1)));
};
let [x0, y0, x1, y1] = region;
if !(x1 > x0 && y1 > y0) {
return Err(refuse("the region is empty".into()));
}
let (w, h) = pg.render_dimensions();
let cache = InterpreterCache::new();
let t = Affine::new(pg.initial_transform(true).as_coeffs());
let mut ctx = Context::new(
t,
Rect::new(0.0, 0.0, w as f64, h as f64),
&cache,
doc.xref(),
InterpreterSettings::default(),
);
let mut dev = Draw {
region: Rect::new(x0, y0, x1, y1),
out: String::new(),
};
interpret_page(pg, &mut ctx, &mut dev);
Ok(format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"{x0:.2} {y0:.2} {:.2} {:.2}\" width=\"{:.2}\" height=\"{:.2}\">\n<rect x=\"{x0:.2}\" y=\"{y0:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"#ffffff\"/>\n{}</svg>\n",
x1 - x0,
y1 - y0,
x1 - x0,
y1 - y0,
x1 - x0,
y1 - y0,
dev.out
))
}
#[cfg(test)]
mod tests {
use super::*;
const PDF: &[u8] = include_bytes!("../tests/fixtures/small.pdf");
fn starts(svg: &str) -> Vec<(f64, f64)> {
(svg.split("<path d=\"M").skip(1))
.filter_map(|r| {
let mut n = r.split(|c: char| c == ' ' || c.is_ascii_alphabetic());
Some((n.next()?.parse().ok()?, n.next()?.parse().ok()?))
})
.collect()
}
#[test]
fn a_bar_cut_from_the_page_has_its_noteheads() {
let r = crate::read_pdf_review(PDF).unwrap();
let b = &r.bars[0];
let [x0, y0, x1, y1] = b.frame;
let svg = page_svg(PDF, b.page, [x0, y0 - 20.0, x1, y1 + 20.0]).unwrap();
assert!(svg.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\""));
let paths = starts(&svg);
let heads: Vec<_> = r.marks.iter().filter(|m| m.bar == "1").collect();
assert_eq!(heads.len(), 5);
for m in heads {
let near = |p: &&(f64, f64)| (p.0 - m.at[0]).abs() < 6.0 && (p.1 - m.at[1]).abs() < 6.0;
assert!(
paths.iter().any(|p| near(&p)),
"no head drawn at {:?}",
m.at
);
}
let far = r.bars[3].frame;
assert!(paths.iter().all(|p| p.0 < far[0] + 1.0 || p.1 < y0 - 25.0));
assert!(page_svg(PDF, 3, [0.0, 0.0, 10.0, 10.0]).is_err());
assert!(page_svg(PDF, 0, [10.0, 0.0, 10.0, 10.0]).is_err());
}
}