//! SVG output: the structure, and a rasterisation of its module path that must decode back. mod common; use common::{decode_gray, logo_png}; use image::{GrayImage, Luma}; use pictor_qr::{Level, QrError, Style, render_rgba, render_svg}; /// The SVG's dark modules as horizontal runs `(x, y, len)` in module units (quiet zone included), parsed from the /// path's `M{x} {y}h{len}v1h-{len}z` segments. fn runs(svg: &str) -> Vec<(u32, u32, u32)> { let start = svg.find(" d=\"").expect("a path with d") + 4; let end = start + svg[start..].find('"').unwrap(); let d = &svg[start..end]; d.split('M') .filter(|s| !s.is_empty()) .map(|seg| { let (xy, rest) = seg.split_once('h').expect("h after M"); let (x, y) = xy.split_once(' ').expect("x y"); let (len, tail) = rest.split_once('v').expect("v after h"); assert_eq!(tail, format!("1h-{len}z"), "segment {seg}"); (x.parse().unwrap(), y.parse().unwrap(), len.parse().unwrap()) }) .collect() } fn view_box_size(svg: &str) -> u32 { let start = svg.find("viewBox=\"0 0 ").unwrap() + 13; let rest = &svg[start..]; rest[..rest.find(' ').unwrap()].parse().unwrap() } fn rasterise(svg: &str, scale: u32) -> GrayImage { let n = view_box_size(svg); let mut img = GrayImage::from_pixel(n * scale, n * scale, Luma([255])); for (x, y, len) in runs(svg) { for py in y * scale..(y + 1) * scale { for px in x * scale..(x + len) * scale { img.put_pixel(px, py, Luma([0])); } } } img } #[test] fn svg_structure() { let text = "Příliš žluťoučký kůň"; let style = Style { size_px: 400, ..Style::default() }; let svg = render_svg(text, Level::M, &style, None).unwrap(); assert!(svg.starts_with("")); assert!(svg.contains("xmlns=\"http://www.w3.org/2000/svg\"")); assert_eq!(svg.matches("