crisol-plot-render 1.8.1

Headless SVG/PNG renderer for Crisol PlotSpec charts, with no window or GPU.
Documentation
//! SVG serialization of renderer primitives.

use std::fmt::Write;

use crisol_core::color::Rgba;
use crisol_plot_core::transform::{ScreenPoint, ScreenRect};

use crate::scene::{Anchor, Prim};
use crate::text;

pub(crate) fn render(scene: &crate::layout::Scene, width: u32, height: u32) -> String {
    let font = text::font().ok();
    let mut out = String::with_capacity(4096);
    let _ = writeln!(
        out,
        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\" viewBox=\"0 0 {width} {height}\">"
    );
    for prim in &scene.prims {
        match prim {
            Prim::Rect { rect, fill, stroke } => {
                out.push_str("<rect ");
                rect_attrs(&mut out, *rect);
                out.push_str(&fill_attr(*fill));
                if let Some((width, color)) = stroke {
                    let _ = write!(out, " stroke=\"{}\" stroke-width=\"{width:.2}\"", hex(*color));
                }
                out.push_str("/>\n");
            }
            Prim::Line { points, width, color } => {
                out.push_str("<polyline ");
                points_attr(&mut out, points);
                let _ = writeln!(
                    out,
                    " fill=\"none\" stroke=\"{}\" stroke-width=\"{width:.2}\" stroke-linejoin=\"round\" stroke-linecap=\"round\"/>",
                    hex(*color)
                );
            }
            Prim::Polygon { points, fill, stroke } => {
                out.push_str("<polygon ");
                points_attr(&mut out, points);
                out.push_str(&fill_attr(*fill));
                if let Some((width, color)) = stroke {
                    let _ = write!(out, " stroke=\"{}\" stroke-width=\"{width:.2}\"", hex(*color));
                }
                out.push_str("/>\n");
            }
            Prim::Circle {
                center,
                radius,
                fill,
                stroke,
            } => {
                let _ = write!(
                    out,
                    "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{radius:.2}\"",
                    center.x, center.y
                );
                out.push_str(&fill_attr(*fill));
                if let Some((width, color)) = stroke {
                    let _ = write!(out, " stroke=\"{}\" stroke-width=\"{width:.2}\"", hex(*color));
                }
                out.push_str("/>\n");
            }
            Prim::Text {
                pos,
                text,
                size,
                color,
                anchor,
            } => {
                let anchor = match anchor {
                    Anchor::Left => "start",
                    Anchor::Center => "middle",
                    Anchor::Right => "end",
                };
                let baseline = font
                    .as_ref()
                    .map_or(pos.y + size * 0.8, |font| pos.y + text::ascent(font, *size));
                let _ = writeln!(
                    out,
                    "<text x=\"{:.2}\" y=\"{baseline:.2}\" font-family=\"DejaVu Sans, sans-serif\" font-size=\"{size:.2}\" fill=\"{}\" text-anchor=\"{anchor}\">{}</text>",
                    pos.x,
                    hex(*color),
                    escape(text)
                );
            }
        }
    }
    out.push_str("</svg>\n");
    out
}

fn rect_attrs(out: &mut String, rect: ScreenRect) {
    let _ = write!(
        out,
        "x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\"",
        rect.left(),
        rect.top(),
        rect.width(),
        rect.height()
    );
}

fn points_attr(out: &mut String, points: &[ScreenPoint]) {
    out.push_str("points=\"");
    for (index, point) in points.iter().enumerate() {
        if index > 0 {
            out.push(' ');
        }
        let _ = write!(out, "{:.2},{:.2}", point.x, point.y);
    }
    out.push('"');
}

fn fill_attr(color: Rgba) -> String {
    let [_, _, _, a] = color.to_array();
    if a == 255 {
        format!(" fill=\"{}\"", hex(color))
    } else if a == 0 {
        " fill=\"none\"".to_owned()
    } else {
        format!(" fill=\"{}\" fill-opacity=\"{:.3}\"", hex(color), f32::from(a) / 255.0)
    }
}

fn hex(color: Rgba) -> String {
    let [r, g, b, a] = color.to_array();
    if a == 0 {
        return "#000000".to_owned();
    }
    let straight = |channel: u8| ((u16::from(channel) * 255 + u16::from(a) / 2) / u16::from(a)).min(255) as u8;
    format!("#{:02x}{:02x}{:02x}", straight(r), straight(g), straight(b))
}

fn escape(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}