garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /gfx/src/font.rs

raw

//! Text from a TrueType font at run time: a glyph's outline (`ttf`) becomes
//! an 8-bit coverage mask the first time it is drawn at a size (`vector`),
//! and the mask is kept, so drawing text after that is blending stored
//! pixels.
//!
//! A line the font can draw by itself, left to right, is drawn glyph by
//! glyph as it always was. Any other (right to left, Arabic, a character
//! the font lacks) is laid out by `pinnacle_text`, with the fallback fonts
//! the program set ([`set_fallbacks`]) for what this one lacks.

use alloc::sync::Arc;
use alloc::vec::Vec;
use core::cell::UnsafeCell;
use core::sync::atomic::{AtomicBool, AtomicPtr, Ordering};

pub use pinnacle_ttf::Font as Face;
use pinnacle_vector::Path;

/// A glyph at a size: its coverage and where it sits from the pen.
pub struct Glyph {
    /// In 1/16 pixel.
    pub advance: i32,
    pub width: i32,
    pub height: i32,
    pub left: i32,
    /// From the baseline up to the mask's top row.
    pub top: i32,
    pub coverage: Vec<u8>,
}

/// The fonts that fill in for any font's missing characters, in the order
/// they are tried: Arabic, Hebrew, CJK, emoji, as a program's theme lists
/// them. `face(i)` reads the `i`th the first time it is asked for.
pub struct Fallbacks {
    pub count: usize,
    /// Which of them is for emoji.
    pub emoji: Option<usize>,
    pub face: fn(usize) -> Option<&'static Face<'static>>,
}

static FALLBACKS: AtomicPtr<Fallbacks> = AtomicPtr::new(core::ptr::null_mut());

/// Sets the fallback fonts for every font of the program.
pub fn set_fallbacks(fallbacks: &'static Fallbacks) {
    FALLBACKS.store(fallbacks as *const Fallbacks as *mut Fallbacks, Ordering::Release);
}

fn fallbacks() -> Option<&'static Fallbacks> {
    // SAFETY: only ever a `&'static Fallbacks`, or null.
    unsafe { FALLBACKS.load(Ordering::Acquire).as_ref() }
}

/// A face at one size, with the glyphs drawn so far.
pub struct Font {
    face: &'static Face<'static>,
    px: f32,
    pub size: i32,
    pub line_height: i32,
    pub ascent: i32,
    pub descent: i32,
    locked: AtomicBool,
    /// By key: a character's (`CHAR` and the character), or a glyph's of
    /// one of the fonts (the font's index above 16 bits, the glyph below).
    glyphs: UnsafeCell<Vec<(u32, Arc<Glyph>)>>,
}

const CHAR: u32 = 1 << 31;

// SAFETY: `glyphs` is only touched with `locked` held.
unsafe impl Sync for Font {}

/// Traces an outline into a vector path.
struct Tracer(Path);

impl pinnacle_ttf::Pen for Tracer {
    fn move_to(&mut self, x: f32, y: f32) {
        self.0.move_to(x, y);
    }
    fn line_to(&mut self, x: f32, y: f32) {
        self.0.line_to(x, y);
    }
    fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
        self.0.quad_to(cx, cy, x, y);
    }
    fn close(&mut self) {
        self.0.close();
    }
}

/// A glyph laid out in a line: what to draw and where its pen is, in
/// 1/16 pixel from the line's start, y down from the baseline.
pub struct Placed {
    pub glyph: Arc<Glyph>,
    pub x: i32,
    pub y: i32,
}

impl Font {
    pub fn new(face: &'static Face<'static>, px: f32) -> Font {
        let (ascent, descent, gap) = face.line_metrics(px);
        Font {
            face,
            px,
            size: (px + 0.5) as i32,
            line_height: (ascent - descent + gap + 0.5) as i32,
            ascent: (ascent + 0.5) as i32,
            descent: (descent - 0.5) as i32,
            locked: AtomicBool::new(false),
            glyphs: UnsafeCell::new(Vec::new()),
        }
    }

    fn with_glyphs<R>(&self, f: impl FnOnce(&mut Vec<(u32, Arc<Glyph>)>) -> R) -> R {
        while self.locked.swap(true, Ordering::Acquire) {
            core::hint::spin_loop();
        }
        // SAFETY: the lock is held.
        let r = f(unsafe { &mut *self.glyphs.get() });
        self.locked.store(false, Ordering::Release);
        r
    }

    /// The face this size is of, to make other sizes of it.
    pub fn face(&self) -> &'static Face<'static> {
        self.face
    }

    /// The glyph kept under `key`, or `draw`n and kept.
    fn kept(&self, key: u32, draw: impl FnOnce(&mut Tracer) -> pinnacle_ttf::Metrics) -> Arc<Glyph> {
        let found = self.with_glyphs(|glyphs| {
            glyphs
                .binary_search_by_key(&key, |(k, _)| *k)
                .map_err(|_| ())
                .map(|i| glyphs[i].1.clone())
        });
        if let Ok(glyph) = found {
            return glyph;
        }
        // Drawn outside the lock: another thread drawing the same glyph
        // only wastes the work.
        let mut tracer = Tracer(Path::new());
        let metrics = draw(&mut tracer);
        let glyph = Arc::new(Glyph {
            advance: (metrics.advance * 16.0 + 0.5) as i32,
            width: metrics.width as i32,
            height: metrics.height as i32,
            left: metrics.xmin,
            top: metrics.height as i32 + metrics.ymin,
            coverage: pinnacle_vector::mask(&tracer.0, metrics.width, metrics.height),
        });
        self.with_glyphs(|glyphs| {
            if let Err(i) = glyphs.binary_search_by_key(&key, |(k, _)| *k) {
                glyphs.insert(i, (key, glyph.clone()));
            }
        });
        glyph
    }

    /// `ch` at this size; a character the font lacks draws as '?'.
    pub fn glyph(&self, ch: char) -> Arc<Glyph> {
        let ch = if ch.is_whitespace() || self.face.glyph_index(ch) != 0 {
            ch
        } else {
            '?'
        };
        self.kept(CHAR | ch as u32, |pen| self.face.outline(ch, self.px, pen))
    }

    /// Glyph `glyph` of font `face` (0 this font, then the fallbacks).
    fn glyph_of(&self, face: usize, glyph: u16) -> Option<Arc<Glyph>> {
        let f = self.font(face)?;
        let key = ((face as u32) << 16) | u32::from(glyph);
        Some(self.kept(key, |pen| f.outline_glyph(glyph, self.px, pen)))
    }

    /// Font `i` of this font's list: itself, then the fallbacks.
    fn font(&self, i: usize) -> Option<&'static Face<'static>> {
        if i == 0 {
            return Some(self.face);
        }
        let f = fallbacks()?;
        (i <= f.count).then(|| (f.face)(i - 1)).flatten()
    }

    /// Whether `text` is drawn as it always was: left to right, every
    /// character this font's own.
    fn plain(&self, text: &str) -> bool {
        pinnacle_text::simple(text)
            && text
                .chars()
                .all(|c| c.is_whitespace() || self.face.glyph_index(c) != 0 || fallbacks().is_none())
    }

    /// `text` laid out: each glyph with its pen, and the line's width, in
    /// 1/16 pixel.
    pub fn layout(&self, text: &str) -> (Vec<Placed>, i32) {
        let mut out = Vec::new();
        if self.plain(text) {
            let mut pen = 0;
            for ch in text.chars() {
                let glyph = self.glyph(ch);
                let advance = glyph.advance;
                out.push(Placed { glyph, x: pen, y: 0 });
                pen += advance;
            }
            return (out, pen);
        }
        let fallbacks = fallbacks();
        let count = 1 + fallbacks.map_or(0, |f| f.count);
        let emoji = fallbacks.and_then(|f| f.emoji).map(|e| e + 1);
        let get = |i: usize| self.font(i);
        let line = pinnacle_text::shape(text, self.px, &get, count, emoji);
        for g in &line.glyphs {
            if let Some(glyph) = self.glyph_of(g.face, g.glyph) {
                out.push(Placed {
                    glyph,
                    x: (g.x * 16.0 + 0.5) as i32,
                    y: (g.y * 16.0 + if g.y < 0.0 { -0.5 } else { 0.5 }) as i32,
                });
            }
        }
        (out, (line.width * 16.0 + 0.5) as i32)
    }

    /// The width of `text` in pixels.
    pub fn measure(&self, text: &str) -> i32 {
        if self.plain(text) {
            return text.chars().map(|c| self.glyph(c).advance).sum::<i32>() / 16;
        }
        self.layout(text).1 / 16
    }

    /// Whether `text`'s first strong letter runs right to left, so that it
    /// is set from the right.
    pub fn rtl(text: &str) -> bool {
        !pinnacle_text::simple(text)
            && pinnacle_text::bidi::paragraph_level(&text.chars().collect::<Vec<_>>()) == 1
    }
}