laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
//! How an SVG becomes pixels.

use std::path::PathBuf;
use std::sync::Arc;

use image::RgbaImage;
use resvg::tiny_skia::{Pixmap, Transform};
use resvg::usvg::fontdb::{Database, Family, Query};
use resvg::usvg::{Options, Tree};

use crate::contracts::Renderer;
use crate::exceptions::RenderFailed;

/// Renders with `resvg`, the Rust renderer, as a library: no binary to install and nothing to spawn.
///
/// The PHP package shells out to `rsvg-convert` or `resvg`. Fonts are the part of that which carried over:
/// `resvg` takes font files, so the same TTF your site ships in `public/fonts` also renders the card, and
/// the output is identical on your laptop and on the server.
pub struct ResvgRenderer {
    fonts: Arc<Database>,
}

impl ResvgRenderer {
    /// A renderer that knows the given font files, and the fonts installed on the machine when
    /// `system_fonts` is set.
    ///
    /// The generic families (`sans-serif`, `serif`, `monospace`, ...) that nothing installed answers to
    /// fall back to the first font file, so a template that asks for `-apple-system, Helvetica, sans-serif`
    /// still draws on a container with no fonts at all.
    pub fn new(font_files: &[PathBuf], system_fonts: bool) -> Self {
        let mut fonts = Database::new();
        let mut fallback: Option<String> = None;

        for file in font_files.iter().filter(|file| file.is_file()) {
            let before = fonts.len();

            if fonts.load_font_file(file).is_ok() && fallback.is_none() {
                fallback = fonts
                    .faces()
                    .nth(before)
                    .and_then(|face| face.families.first().map(|(name, _)| name.clone()));
            }
        }

        if system_fonts {
            fonts.load_system_fonts();
        }

        if let Some(family) = fallback {
            Self::fall_back(&mut fonts, &family);
        }

        Self { fonts: Arc::new(fonts) }
    }

    fn fall_back(fonts: &mut Database, family: &str) {
        let answers = |fonts: &Database, generic: Family<'_>| {
            fonts
                .query(&Query {
                    families: &[generic],
                    ..Query::default()
                })
                .is_some()
        };

        if !answers(fonts, Family::SansSerif) {
            fonts.set_sans_serif_family(family);
        }

        if !answers(fonts, Family::Serif) {
            fonts.set_serif_family(family);
        }

        if !answers(fonts, Family::Monospace) {
            fonts.set_monospace_family(family);
        }

        if !answers(fonts, Family::Cursive) {
            fonts.set_cursive_family(family);
        }

        if !answers(fonts, Family::Fantasy) {
            fonts.set_fantasy_family(family);
        }
    }
}

impl Renderer for ResvgRenderer {
    /// Draws the SVG at exactly `width` by `height`, stretching it if its own size has another shape,
    /// like `rsvg-convert --width --height` does.
    fn render(&self, svg: &str, width: u32, height: u32) -> Result<RgbaImage, RenderFailed> {
        let options = Options {
            fontdb: Arc::clone(&self.fonts),
            font_family: "sans-serif".to_owned(),
            ..Options::default()
        };
        let tree = Tree::from_str(svg, &options)
            .map_err(|error| RenderFailed::new(format!("resvg failed to parse the card: {error}")))?;
        let mut pixmap =
            Pixmap::new(width, height).ok_or_else(|| RenderFailed::new("Laracards: the card has no size."))?;
        let size = tree.size();

        resvg::render(
            &tree,
            Transform::from_scale(width as f32 / size.width(), height as f32 / size.height()),
            &mut pixmap.as_mut(),
        );

        let mut pixels = Vec::with_capacity(pixmap.pixels().len() * 4);

        for pixel in pixmap.pixels() {
            let color = pixel.demultiply();

            pixels.extend_from_slice(&[color.red(), color.green(), color.blue(), color.alpha()]);
        }

        RgbaImage::from_raw(width, height, pixels)
            .ok_or_else(|| RenderFailed::new("Laracards: the render has the wrong size."))
    }
}