Skip to main content

mln_engine/text/
shaper.rs

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