Skip to main content

mln_engine/text/
shaper.rs

1// Text shapes with HarfRust on the face's font, with its own character map
2// and advances, at 24 px in 26.6 fixed point, and:
3// - the font's tables, including the AAT ones (morx, kerx, trak and the
4//   rest) and `kern`: some system fonts, like Apple's Tibetan font Kailasa,
5//   shape only through `morx`;
6// - user features `frac=0`, `numr=0`, `dnom=0`, so that no automatic
7//   fraction features apply;
8// - no glyph extents, which keeps HarfRust's fallback mark positioning from
9//   moving marks.
10// A variable font shapes at its weight (regular unless made
11// `Shaper::at_weight`), with its GSUB/GPOS feature variations.
12
13use std::sync::Arc;
14
15use harfrust::{
16    Buffer, Direction, Feature, FontFuncs, GlyphExtents, GlyphId, Language, Script, ShapeOptions, ShapePlan,
17    ShaperFont, Tag,
18};
19use mln_style::hash::HashMap;
20use parking_lot::Mutex;
21use unicode_properties::{GeneralCategory, UnicodeGeneralCategory};
22
23use crate::text::face::{Face, SDF_FONT_SIZE};
24use crate::text::glyph::{FontData, Glyph, GlyphID, GlyphIDType};
25
26/// Where a shaped glyph goes, in pixels at 24 px: its offset from the pen,
27/// and how far it moves the pen.
28#[derive(Clone, Copy, PartialEq, Debug, Default, mln_wire::Wire)]
29pub struct GlyphAdjust {
30    pub x_offset: f32,
31    pub y_offset: f32,
32    pub advance: f32,
33}
34
35impl GlyphAdjust {
36    #[must_use]
37    pub fn new(x_offset: f32, y_offset: f32, advance: f32) -> Self {
38        GlyphAdjust { x_offset, y_offset, advance }
39    }
40}
41
42/// Shaped text: its glyphs in visual order, and where each goes.
43#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
44pub struct ShapedText {
45    pub glyphs: Vec<GlyphID>,
46    pub adjusts: Vec<GlyphAdjust>,
47}
48
49/// The language all text shapes in: "c", the C locale's.
50fn default_language() -> Language {
51    Language::new("c").expect("non-empty")
52}
53
54/// The script of `c`, as an ISO 15924 tag. Combining marks inherit the
55/// script of their bases, regardless of their own script. Uses the Unicode
56/// version of HarfRust's own tables.
57#[must_use]
58pub(crate) fn unicode_script(c: char) -> [u8; 4] {
59    if c.general_category() == GeneralCategory::NonspacingMark {
60        return Script::INHERITED.tag().to_be_bytes();
61    }
62    harfrust::unicode::script(u32::from(c)).tag().to_be_bytes()
63}
64
65/// Shape plans by script tag and right-to-left direction.
66type ShapePlans = HashMap<([u8; 4], bool), Arc<ShapePlan>>;
67
68/// A font file that shapes text with HarfRust and draws its glyphs.
69pub struct Shaper {
70    type_: GlyphIDType,
71    face: Face,
72    /// Shape plans, cached per segment properties (script and direction).
73    plans: Mutex<ShapePlans>,
74}
75
76/// The user features that turn off the fraction features.
77fn no_fraction_features() -> [Feature; 3] {
78    [
79        Feature::new(Tag::new(b"frac"), 0, ..),
80        Feature::new(Tag::new(b"numr"), 0, ..),
81        Feature::new(Tag::new(b"dnom"), 0, ..),
82    ]
83}
84
85/// The font's own glyph mapping and advances, without glyph extents.
86struct NoGlyphExtents;
87
88impl FontFuncs for NoGlyphExtents {
89    fn glyph_extents(&self, _font: &ShaperFont, _glyph: GlyphId) -> Option<GlyphExtents> {
90        None
91    }
92}
93
94impl Shaper {
95    /// A shaper for the font in `data`, whose glyphs have type `type_`. It
96    /// keeps `data` instead of copying it.
97    pub fn new(type_: GlyphIDType, data: impl Into<FontData>) -> Self {
98        Shaper::at_weight(type_, data, crate::text::weight::REGULAR_WEIGHT)
99    }
100
101    /// [`Shaper::new`], with a variable font at the OpenType `weight` within
102    /// its `wght` axis rather than at regular weight.
103    pub fn at_weight(type_: GlyphIDType, data: impl Into<FontData>, weight: f32) -> Self {
104        Shaper { type_, face: Face::new(data, weight), plans: Mutex::new(HashMap::default()) }
105    }
106
107    /// Whether the data is a font the shaper reads.
108    #[must_use]
109    pub fn valid(&self) -> bool {
110        self.face.is_valid()
111    }
112
113    /// The glyph the font maps `c` to, unshaped: `None` unless it has one
114    /// that the shaper draws, a glyph other than `.notdef` with an outline
115    /// it reads.
116    #[must_use]
117    pub fn glyph_of(&self, c: char) -> Option<GlyphID> {
118        Some(GlyphID::with_type(self.face.glyph_of(c)?, self.type_))
119    }
120
121    /// The glyph's coverage at 24 px, before the signed distance field.
122    #[must_use]
123    pub fn rasterize_glyph(&self, glyph: GlyphID) -> Glyph {
124        self.face.rasterize_glyph(glyph)
125    }
126
127    fn plan(
128        &self,
129        font: &harfrust::Font,
130        script: [u8; 4],
131        rtl: bool,
132        language: &Language,
133        features: &[Feature],
134    ) -> Arc<ShapePlan> {
135        let mut plans = self.plans.lock();
136        Arc::clone(plans.entry((script, rtl)).or_insert_with(|| {
137            Arc::new(ShapePlan::new(font, direction(rtl), Some(to_script(script)), Some(language), features))
138        }))
139    }
140
141    /// Appends the glyphs of `text`, one run of one direction in logical
142    /// order, and where each goes. Glyphs come back in visual order, so a
143    /// right-to-left run's glyphs come back reversed.
144    pub fn shape(&self, text: &[char], rtl: bool, shaped: &mut ShapedText) {
145        struct TextPart {
146            text: Vec<char>,
147            script: [u8; 4],
148        }
149
150        // No script, for a part that holds no letters yet.
151        const INVALID: [u8; 4] = [0; 4];
152
153        if text.is_empty() {
154            return;
155        }
156        // An invalid font shapes nothing.
157        let Some(font) = self.face.font() else {
158            return;
159        };
160
161        let is_neutral = |script: &[u8; 4]| matches!(script, b"Zyyy" | b"Zinh" | b"Zzzz");
162
163        let mut text_parts: Vec<TextPart> = Vec::new();
164        if rtl {
165            // A right-to-left run may hold more than one script, such as
166            // Hebrew and Arabic. Each script is shaped on its own, so the
167            // font applies that script's rules, such as Arabic joining.
168            // Spaces, punctuation, and marks belong to the letters before
169            // them, or to the first letters.
170            for &ch in text {
171                let script = unicode_script(ch);
172                let part_script = if is_neutral(&script) { INVALID } else { script };
173                match text_parts.last_mut() {
174                    Some(last) if part_script == INVALID || last.script == script || last.script == INVALID => {
175                        if last.script == INVALID {
176                            last.script = part_script;
177                        }
178                        last.text.push(ch);
179                    }
180                    _ => text_parts.push(TextPart { text: vec![ch], script: part_script }),
181                }
182            }
183            for text_part in &mut text_parts {
184                if text_part.script == INVALID {
185                    text_part.script = *b"Arab";
186                }
187            }
188            // HarfRust returns each part's glyphs in visual order, and the
189            // run's later parts lie to the left of its earlier ones.
190            text_parts.reverse();
191        } else {
192            for &ch in text {
193                let script = unicode_script(ch);
194                match text_parts.last_mut() {
195                    Some(last) if last.script == script || script == *b"Zinh" => last.text.push(ch),
196                    _ => text_parts.push(TextPart { text: vec![ch], script }),
197                }
198            }
199        }
200
201        for text_part in &text_parts {
202            let Some(buffer) = self.shape_part(font, &text_part.text, text_part.script, rtl) else {
203                continue;
204            };
205
206            let glyph_info = buffer.glyph_infos();
207            let glyph_pos = buffer.glyph_positions();
208            shaped.glyphs.reserve(glyph_info.len());
209            shaped.adjusts.reserve(glyph_info.len());
210            for (info, pos) in glyph_info.iter().zip(glyph_pos) {
211                shaped.glyphs.push(GlyphID::with_type(info.glyph_id as u16, self.type_));
212                shaped.adjusts.push(GlyphAdjust {
213                    x_offset: pos.x_offset as f32 / 64.0,
214                    y_offset: pos.y_offset.wrapping_neg() as f32 / 64.0,
215                    advance: pos.x_advance as f32 / 64.0,
216                });
217            }
218        }
219    }
220
221    /// Shapes one part of a run, of one script.
222    fn shape_part(&self, font: &harfrust::Font, text: &[char], script: [u8; 4], rtl: bool) -> Option<Buffer> {
223        let shaper_font = ShaperFont::new(font).with_scale(SDF_FONT_SIZE * 64).with_font_funcs(Some(&NoGlyphExtents));
224        let language = default_language();
225        let features = no_fraction_features();
226
227        let mut buffer = Buffer::new();
228        buffer.set_direction(direction(rtl));
229        buffer.set_script(Some(to_script(script)));
230        buffer.set_language(Some(language.clone()));
231        // Each character is a cluster of its own, with no pre- or
232        // post-context.
233        for (cluster, &c) in (0..).zip(text) {
234            buffer.push(u32::from(c), cluster);
235        }
236
237        let plan = self.plan(font, script, rtl, &language, &features);
238        let options = ShapeOptions::new().plan(Some(&plan)).features(&features);
239        // hb_shape cannot fail on a valid buffer; HarfRust only fails on
240        // plan/buffer mismatches, which cannot happen here.
241        harfrust::shape(&shaper_font, &mut buffer, options).ok()?;
242        Some(buffer)
243    }
244}
245
246/// The direction of a run.
247fn direction(rtl: bool) -> Direction {
248    if rtl { Direction::RightToLeft } else { Direction::LeftToRight }
249}
250
251/// A script tag as a HarfRust script.
252fn to_script(tag: [u8; 4]) -> Script {
253    Script::from_iso15924_tag(Tag::new(&tag)).unwrap_or(Script::UNKNOWN)
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    #[test]
261    fn script_segmentation_classifies_characters() {
262        assert_eq!(&unicode_script('a'), b"Latn");
263        assert_eq!(&unicode_script(' '), b"Zyyy");
264        assert_eq!(&unicode_script('\u{0301}'), b"Zinh");
265        assert_eq!(&unicode_script('\u{0941}'), b"Zinh"); // Devanagari vowel sign U (Mn)
266        assert_eq!(&unicode_script('\u{0627}'), b"Arab");
267        assert_eq!(&unicode_script('\u{4E2D}'), b"Hani");
268        assert_eq!(&unicode_script('\u{AC00}'), b"Hang");
269        assert_eq!(&unicode_script('\u{20000}'), b"Hani"); // CJK Extension B
270        assert_eq!(&unicode_script('\u{1F600}'), b"Zyyy");
271    }
272}