use lievisual::geometry::Color;
use lievisual::render::{Renderer, SvgRenderer};
pub fn render_scene_svg(scene: &lievisual::Scene) -> String {
let mut renderer =
SvgRenderer::new(scene.width, scene.height).with_background(Color::TRANSPARENT);
renderer.render_scene(scene);
to_official_svg(renderer.into_string(), scene.width, scene.height)
}
fn to_official_svg(svg: String, width: f64, height: f64) -> String {
let mut out = svg;
if let Some(start) = out.find("<svg")
&& let Some(end) = out[start..].find('>').map(|i| start + i)
{
let tag = &out[start..end];
let new_tag = tag
.split_whitespace()
.map(|a| {
if a.starts_with("width=") {
r##"width="100%""##
} else {
a
}
})
.collect::<Vec<_>>()
.join(" ");
let rest = out[end..].to_string();
out = format!(
"{new_tag} style=\"max-width: {width:.3}px; background-color: transparent;\"{rest}"
);
}
out = strip_canvas_background_rect(out, width, height);
out
}
fn strip_canvas_background_rect(svg: String, width: f64, height: f64) -> String {
let prefix = format!(
r##"<rect x="0" y="0" width="{:.2}" height="{:.2}""##,
width, height
);
match svg.find(&prefix) {
Some(start) => {
if let Some(rel) = svg[start..].find("/>") {
let end = start + rel + 2;
let mut out = String::with_capacity(svg.len());
out.push_str(&svg[..start]);
out.push_str(&svg[end..]);
out.replace("\r\n\r\n", "\r\n")
} else {
svg
}
}
None => svg,
}
}
pub fn render_scene_png(scene: &lievisual::Scene) -> Vec<u8> {
use lievisual::render::VelloPixmapRenderer;
let w = (scene.width.round() as i64).max(1) as u32;
let h = (scene.height.round() as i64).max(1) as u32;
let mut renderer = VelloPixmapRenderer::new(w, h).with_background(scene.background);
renderer.render_png(scene)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn svg_is_nonempty() {
let scene = lievisual::Scene::new(100.0, 100.0);
assert!(!render_scene_svg(&scene).is_empty());
}
}