laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
use std::path::{Path, PathBuf};

use resvg::tiny_skia::{Path as SkPath, PathBuilder};
use ttf_parser::{Face, GlyphId, OutlineBuilder};

/// What a fitted block came out as.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fit {
    /// The wrapped lines.
    pub lines: Vec<String>,
    /// The largest candidate size that fit.
    pub size: i32,
}

/// How far the glyphs of a face reach above and below the baseline, in pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Metrics {
    /// Above the baseline.
    pub ascent: i32,
    /// Below the baseline.
    pub descent: i32,
}

/// Wraps a title into a fixed number of lines and picks the largest font size that still fits.
///
/// The width is measured with the real font instead of estimated from a character count. That
/// difference is why "IIIIII" and "MMMMMM" no longer get the same budget, and why wide titles stop
/// overflowing the card. The PHP package asks GD, which wants point sizes; here the face is read with
/// `ttf-parser` and a size is the pixel size an SVG `font-size` means, so there is no conversion.
pub struct TextFitter {
    path: PathBuf,
    data: Vec<u8>,
}

impl TextFitter {
    /// Read a font file.
    ///
    /// # Errors
    ///
    /// Fails when the file is missing or is not a font.
    pub fn new(font_path: impl AsRef<Path>) -> laravel::Result<Self> {
        let path = font_path.as_ref();

        if !path.is_file() {
            return Err(laravel::Error::msg(format!(
                "Laracards: font file not found at {}.",
                path.display()
            )));
        }

        let data = std::fs::read(path)?;

        Face::parse(&data, 0).map_err(|error| {
            laravel::Error::msg(format!("Laracards: {} is not a usable font: {error}.", path.display()))
        })?;

        Ok(Self {
            path: path.to_path_buf(),
            data,
        })
    }

    /// The font file.
    pub fn font_path(&self) -> &Path {
        &self.path
    }

    fn face(&self) -> Face<'_> {
        Face::parse(&self.data, 0).expect("the face was parsed when the fitter was built")
    }

    /// Ascent and descent of the face at `size`, in pixels.
    ///
    /// Needed to place a line without an SVG to do it: a layout is described in boxes, but text is drawn
    /// on a baseline, so centring a block means knowing how far above and below it the glyphs reach.
    /// It is measured on "Hg", like the PHP package.
    pub fn metrics(&self, size: i32) -> Metrics {
        let face = self.face();
        let scale = f64::from(size) / f64::from(face.units_per_em());
        let reach = |character: char| {
            face.glyph_index(character)
                .and_then(|glyph| face.glyph_bounding_box(glyph))
        };
        let (mut top, mut bottom) = (f64::from(face.ascender()), f64::from(face.descender()));

        if let (Some(h), Some(g)) = (reach('H'), reach('g')) {
            top = f64::from(h.y_max.max(g.y_max));
            bottom = f64::from(h.y_min.min(g.y_min));
        }

        Metrics {
            ascent: (top * scale).ceil().max(0.0) as i32,
            descent: (-bottom * scale).ceil().max(0.0) as i32,
        }
    }

    /// Wraps `text` into at most `max_lines` lines, with the largest of `sizes` that fits. When even the
    /// smallest does not, the smallest is kept and the last line is ellipsized.
    pub fn fit(&self, text: &str, max_width: i32, max_lines: usize, sizes: &[i32]) -> Fit {
        let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
        let smallest = sizes.last().copied().unwrap_or(0);

        if text.is_empty() {
            return Fit {
                lines: Vec::new(),
                size: smallest,
            };
        }

        for &size in sizes {
            let lines = self.wrap(&text, max_width, size);

            if lines.len() <= max_lines {
                return Fit { lines, size };
            }
        }

        let mut lines: Vec<String> = self
            .wrap(&text, max_width, smallest)
            .into_iter()
            .take(max_lines)
            .collect();

        if let Some(last) = lines.last_mut() {
            *last = self.ellipsize(last, max_width, smallest);
        }

        Fit { lines, size: smallest }
    }

    /// Breaks text into lines that fit `max_width` at `size`, never splitting words unless a single word
    /// is itself wider than the line.
    pub fn wrap(&self, text: &str, max_width: i32, size: i32) -> Vec<String> {
        let mut lines = Vec::new();
        let mut current = String::new();

        for word in text.split(' ') {
            let candidate = if current.is_empty() {
                word.to_owned()
            } else {
                format!("{current} {word}")
            };

            if self.width(&candidate, size) <= max_width {
                current = candidate;

                continue;
            }

            if !current.is_empty() {
                lines.push(std::mem::take(&mut current));
            }

            if self.width(word, size) > max_width {
                let mut pieces = self.break_word(word, max_width, size);

                current = pieces.pop().unwrap_or_default();
                lines.extend(pieces);

                continue;
            }

            current = word.to_owned();
        }

        if !current.is_empty() {
            lines.push(current);
        }

        lines
    }

    /// Rendered width of `text` at `size`, in whole pixels, rounded up so a line that measures as fitting
    /// always does.
    pub fn width(&self, text: &str, size: i32) -> i32 {
        if text.is_empty() {
            return 0;
        }

        let face = self.face();

        self.advance(&face, text, size).ceil() as i32
    }

    fn advance(&self, face: &Face<'_>, text: &str, size: i32) -> f64 {
        let scale = f64::from(size) / f64::from(face.units_per_em());
        let mut total = 0.0;
        let mut previous: Option<GlyphId> = None;

        for character in text.chars() {
            let glyph = face.glyph_index(character).unwrap_or(GlyphId(0));

            if let Some(left) = previous {
                total += f64::from(Self::kerning(face, left, glyph)) * scale;
            }

            total += f64::from(face.glyph_hor_advance(glyph).unwrap_or(0)) * scale;
            previous = Some(glyph);
        }

        total
    }

    /// Pair kerning from the legacy `kern` table. Faces that only kern through GPOS measure unkerned.
    fn kerning(face: &Face<'_>, left: GlyphId, right: GlyphId) -> i16 {
        face.tables()
            .kern
            .and_then(|table| {
                table
                    .subtables
                    .into_iter()
                    .filter(|subtable| subtable.horizontal && !subtable.variable)
                    .find_map(|subtable| subtable.glyphs_kerning(left, right))
            })
            .unwrap_or(0)
    }

    /// The outline of `text` at `size`, with its baseline on y = 0 and its start on x = 0, y growing
    /// downwards. `None` for text with nothing to draw, such as spaces.
    pub fn outline(&self, text: &str, size: i32) -> Option<SkPath> {
        let face = self.face();
        let scale = size as f32 / f32::from(face.units_per_em());
        let mut builder = Outline {
            path: PathBuilder::new(),
            scale,
            origin: 0.0,
        };
        let mut previous: Option<GlyphId> = None;

        for character in text.chars() {
            let glyph = face.glyph_index(character).unwrap_or(GlyphId(0));

            if let Some(left) = previous {
                builder.origin += f32::from(Self::kerning(&face, left, glyph)) * scale;
            }

            face.outline_glyph(glyph, &mut builder);
            builder.origin += f32::from(face.glyph_hor_advance(glyph).unwrap_or(0)) * scale;
            previous = Some(glyph);
        }

        builder.path.finish()
    }

    fn break_word(&self, word: &str, max_width: i32, size: i32) -> Vec<String> {
        let mut pieces = Vec::new();
        let mut current = String::new();

        for character in word.chars() {
            if !current.is_empty() && self.width(&format!("{current}{character}"), size) > max_width {
                pieces.push(std::mem::take(&mut current));
                current.push(character);

                continue;
            }

            current.push(character);
        }

        if !current.is_empty() {
            pieces.push(current);
        }

        pieces
    }

    fn ellipsize(&self, line: &str, max_width: i32, size: i32) -> String {
        let mut line = line.trim_end_matches([' ', '.', ',', ';', ':']).to_owned();

        while !line.is_empty() && self.width(&format!("{line}..."), size) > max_width {
            line.pop();
        }

        format!("{}...", line.trim_end())
    }
}

/// Collects a glyph outline, which grows upwards in font units, as a path that grows downwards in pixels.
struct Outline {
    path: PathBuilder,
    scale: f32,
    origin: f32,
}

impl Outline {
    fn x(&self, x: f32) -> f32 {
        self.origin + x * self.scale
    }

    fn y(&self, y: f32) -> f32 {
        -y * self.scale
    }
}

impl OutlineBuilder for Outline {
    fn move_to(&mut self, x: f32, y: f32) {
        self.path.move_to(self.x(x), self.y(y));
    }

    fn line_to(&mut self, x: f32, y: f32) {
        self.path.line_to(self.x(x), self.y(y));
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        self.path.quad_to(self.x(x1), self.y(y1), self.x(x), self.y(y));
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        self.path
            .cubic_to(self.x(x1), self.y(y1), self.x(x2), self.y(y2), self.x(x), self.y(y));
    }

    fn close(&mut self) {
        self.path.close();
    }
}