garage44.eu/jeroen/pinnacle

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

.. /text/src/shape.rs

raw

//! A line of text to glyphs: bidi levels, a font for each character, runs
//! shaped by their fonts' rules, and each glyph's place, left to right as
//! it is drawn.
//!
//! The fonts are a list: the first is the one asked for (the system's sans
//! or mono), the others fall back in order for what it lacks. A font is
//! asked for only when a character needs one it has not tried, so a
//! program that never shows Chinese never reads the Chinese font.
//!
//! Latin, Greek, Cyrillic and CJK runs are set glyph by glyph from the
//! character map and advances, as the system always drew them; the scripts
//! whose letters join or stack (Arabic, Hebrew, Syriac, Thaana, N'Ko) and
//! emoji sequences go through the font's `GSUB` and `GPOS`.

use alloc::vec;
use alloc::vec::Vec;

use pinnacle_ttf::Font as Face;
use pinnacle_ttf::layout::{Buffer, Info, Layout, Table};

use crate::arabic::{Form, forms};
use crate::bidi;
use crate::{Script, default_ignorable, emoji_presentation, script};

/// A glyph placed: which font and glyph, where its origin is from the
/// line's start on the baseline (pixels, y down), and which character of
/// the text it came from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Glyph {
    pub face: usize,
    pub glyph: u16,
    pub x: f32,
    pub y: f32,
    pub cluster: usize,
}

/// A line laid out.
#[derive(Clone, Debug, Default)]
pub struct Line {
    /// In the order they are drawn, left to right.
    pub glyphs: Vec<Glyph>,
    /// Its width in pixels.
    pub width: f32,
    /// Its paragraph runs right to left (its first strong letter does).
    pub rtl: bool,
}

const GLOBAL: u32 = 1;
const ISOL: u32 = 2;
const INIT: u32 = 4;
const MEDI: u32 = 8;
const FINA: u32 = 16;

/// The variation selector asking for emoji, and the joiners.
const VS16: char = '\u{fe0f}';
const ZWJ: char = '\u{200d}';
const ZWNJ: char = '\u{200c}';

/// What a run of the line is: its characters (logical, `start..end`), its
/// level, font and script.
#[derive(Clone, Copy, Debug)]
struct Run {
    start: usize,
    end: usize,
    level: u8,
    face: usize,
    script: Script,
}

/// Fonts asked for by index, each read at most once by whoever answers.
struct Fonts<'a, 'f> {
    get: &'a dyn Fn(usize) -> Option<&'f Face<'f>>,
    count: usize,
    tried: Vec<Option<Option<&'f Face<'f>>>>,
}

impl<'f> Fonts<'_, 'f> {
    fn face(&mut self, i: usize) -> Option<&'f Face<'f>> {
        if i >= self.count {
            return None;
        }
        if self.tried[i].is_none() {
            self.tried[i] = Some((self.get)(i));
        }
        self.tried[i].flatten()
    }

    fn has(&mut self, i: usize, c: char) -> bool {
        self.face(i).is_some_and(|f| f.glyph_index(c) != 0)
    }
}

/// Lays out `text` (one line) at `px` pixels to the em. `faces(i)` is the
/// `i`th of `count` fonts, `None` if it is not there; `emoji` says which
/// of them is for emoji, taken first for what is shown as one.
pub fn shape<'f>(
    text: &str,
    px: f32,
    faces: &dyn Fn(usize) -> Option<&'f Face<'f>>,
    count: usize,
    emoji: Option<usize>,
) -> Line {
    let mut fonts = Fonts {
        get: faces,
        count,
        tried: vec![None; count],
    };
    let mut chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    if n == 0 {
        return Line::default();
    }

    let (levels, removed, rtl) = if bidi::any_rtl(text) {
        let p = bidi::paragraph(&chars, None);
        (p.levels, p.removed, p.level % 2 == 1)
    } else {
        (
            vec![0; n],
            chars.iter().map(|&c| bidi::class(c) == bidi::Class::BN).collect(),
            false,
        )
    };
    // L4: a bracket in right-to-left text is drawn as its mirror.
    for i in 0..n {
        if levels[i] % 2 == 1 {
            chars[i] = bidi::mirror(chars[i]);
        }
    }

    // A font for each character.
    let mut face_of = vec![0usize; n];
    for i in 0..n {
        let c = chars[i];
        let prev = if i > 0 { Some(face_of[i - 1]) } else { None };
        let follows = matches!(script(c), Script::Inherited)
            || matches!(c, VS16 | ZWJ | ZWNJ)
            || (0x1f3fb..=0x1f3ff).contains(&(c as u32))
            || removed[i]
            || default_ignorable(c);
        face_of[i] = if let Some(p) = prev.filter(|&p| follows && (fonts.has(p, c) || default_ignorable(c))) {
            p
        } else if let Some(e) = emoji.filter(|&e| {
            (emoji_presentation(c) || chars.get(i + 1) == Some(&VS16) || prev == Some(e) && is_emoji_part(c))
                && fonts.has(e, c)
        }) {
            e
        } else if let Some(p) = prev.filter(|&p| script(c) == Script::Common && fonts.has(p, c)) {
            p
        } else {
            (0..count).find(|&k| fonts.has(k, c)).unwrap_or(prev.unwrap_or(0))
        };
    }

    // Each character's script: punctuation and marks take their
    // neighbours'.
    let mut scripts: Vec<Script> = chars.iter().map(|&c| script(c)).collect();
    let first = scripts
        .iter()
        .copied()
        .find(|s| !matches!(s, Script::Common | Script::Inherited))
        .unwrap_or(Script::Common);
    let mut last = first;
    for s in scripts.iter_mut() {
        if matches!(s, Script::Common | Script::Inherited) {
            *s = last;
        } else {
            last = *s;
        }
    }

    // Runs: one level, one font, one script.
    let mut runs: Vec<Run> = Vec::new();
    for i in 0..n {
        let (level, face, script) = (levels[i], face_of[i], scripts[i]);
        match runs.last_mut() {
            Some(r) if r.level == level && r.face == face && r.script == script => r.end = i + 1,
            _ => runs.push(Run {
                start: i,
                end: i + 1,
                level,
                face,
                script,
            }),
        }
    }

    // L2 over the runs, then each right-to-left run reversed inside.
    let run_levels: Vec<u8> = runs.iter().map(|r| r.level).collect();
    let order = bidi::visual_order(&run_levels, &vec![false; runs.len()]);

    let mut out = Line {
        rtl,
        ..Line::default()
    };
    let mut pen = 0.0f32;
    for &r in &order {
        let run = runs[r];
        let Some(face) = fonts.face(run.face).or_else(|| fonts.face(0)) else {
            continue;
        };
        let complex = run.script.complex() || Some(run.face) == emoji;
        let buffer = shape_run(face, &chars, &removed, run, complex);
        let scale = px / face.units_per_em();
        let rtl = run.level % 2 == 1;
        // Glyphs not attached to another, in the order they are drawn.
        let mut placed: Vec<Option<(f32, f32)>> = vec![None; buffer.len()];
        let visual: Vec<usize> = if rtl {
            (0..buffer.len()).rev().collect()
        } else {
            (0..buffer.len()).collect()
        };
        for &k in &visual {
            let info = &buffer[k];
            if info.attached.is_some() {
                continue;
            }
            placed[k] = Some((pen + info.dx as f32 * scale, -(info.dy as f32) * scale));
            pen += info.advance as f32 * scale;
        }
        // Marks, from the glyph they sit on (always before them).
        for k in 0..buffer.len() {
            if let Some(t) = buffer[k].attached {
                let (bx, by) = placed.get(t as usize).copied().flatten().unwrap_or((pen, 0.0));
                placed[k] = Some((bx + buffer[k].dx as f32 * scale, by - buffer[k].dy as f32 * scale));
            }
        }
        for &k in &visual {
            let info = &buffer[k];
            let cluster = info.cluster as usize;
            if default_ignorable(chars.get(cluster).copied().unwrap_or(' ')) && info.attached.is_none() {
                continue;
            }
            if let Some((x, y)) = placed[k] {
                out.glyphs.push(Glyph {
                    face: run.face,
                    glyph: info.glyph,
                    x,
                    y,
                    cluster,
                });
            }
        }
    }
    out.width = pen;
    out
}

/// What may follow an emoji and stay in its font: joiners, selectors, skin
/// tones, tags, keycaps, regional indicators.
fn is_emoji_part(c: char) -> bool {
    matches!(c as u32, 0x200d | 0xfe0f | 0x20e3 | 0x1f3fb..=0x1f3ff | 0x1f1e6..=0x1f1ff | 0xe0020..=0xe007f)
        || crate::pictographic(c)
}

/// One run through its font: glyphs from the character map, then, for the
/// scripts that need them, the font's substitutions and positions.
fn shape_run(face: &Face, chars: &[char], removed: &[bool], run: Run, complex: bool) -> Buffer {
    let text = &chars[run.start..run.end];
    let form = if complex && matches!(run.script, Script::Arabic | Script::Syriac | Script::Nko) {
        forms(text)
    } else {
        vec![Form::None; text.len()]
    };
    let upem = face.units_per_em();
    let mut buffer: Buffer = Vec::with_capacity(text.len());
    for (k, &c) in text.iter().enumerate() {
        let mut glyph = face.glyph_index(c);
        if glyph == 0 {
            if default_ignorable(c) || removed[run.start + k] {
                continue;
            }
            glyph = face.glyph_index('?');
        }
        let mask = GLOBAL
            | match form[k] {
                Form::None => 0,
                Form::Isolated => ISOL,
                Form::Initial => INIT,
                Form::Medial => MEDI,
                Form::Final => FINA,
            };
        buffer.push(Info {
            glyph,
            cluster: (run.start + k) as u32,
            mask,
            ..Info::default()
        });
    }
    let layout = Layout::new(face);
    if complex && layout.has(Table::Gsub) {
        // In stages, as Arabic wants them: the forms after composition,
        // each form by itself, then the ligatures.
        let stages: [&[([u8; 4], u32)]; 7] = [
            &[(*b"ccmp", GLOBAL), (*b"locl", GLOBAL)],
            &[(*b"isol", ISOL)],
            &[(*b"fina", FINA)],
            &[(*b"medi", MEDI)],
            &[(*b"init", INIT)],
            &[(*b"rlig", GLOBAL)],
            &[(*b"calt", GLOBAL), (*b"liga", GLOBAL), (*b"mset", GLOBAL)],
        ];
        for features in stages {
            let lookups = layout.lookups(Table::Gsub, run.script.tag(), features);
            layout.apply(Table::Gsub, &lookups, &mut buffer);
        }
    }
    for info in buffer.iter_mut() {
        // A joiner or selector the font has a glyph for still takes no room.
        let ignorable = chars
            .get(info.cluster as usize)
            .is_some_and(|&c| default_ignorable(c));
        info.advance = if ignorable {
            0
        } else {
            face.glyph_advance(info.glyph, upem) as i32
        };
    }
    if complex && layout.has(Table::Gpos) {
        // Marks take no room of their own: they sit on their letter.
        for info in buffer.iter_mut() {
            if layout.class(info.glyph) == 3 {
                info.advance = 0;
            }
        }
        let features = [(*b"kern", GLOBAL), (*b"mark", GLOBAL), (*b"mkmk", GLOBAL)];
        let lookups = layout.lookups(Table::Gpos, run.script.tag(), &features);
        layout.apply(Table::Gpos, &lookups, &mut buffer);
    }
    buffer
}

/// The width of a line in pixels, as [`shape`] lays it out.
pub fn width<'f>(
    text: &str,
    px: f32,
    faces: &dyn Fn(usize) -> Option<&'f Face<'f>>,
    count: usize,
    emoji: Option<usize>,
) -> f32 {
    shape(text, px, faces, count, emoji).width
}