Skip to main content

f_office_fonts/
shape.rs

1//! The glyphs of a text by the font's OpenType layout tables (`GSUB` and `GPOS`).
2//!
3//! This module is the only place that names the shaping crate. Layout and the outputs see
4//! [`ShapeRequest`], [`ShapedGlyph`] and [`ShapeFailure`] only.
5
6use std::fmt;
7
8use harfrust::{Buffer, Direction, Language, Script, ShapeOptions, ShaperFont};
9
10use crate::face::Face;
11use crate::{FontDb, FontId};
12
13/// A script whose text goes through the font's layout tables. The set is closed: a
14/// character of no listed script keeps the glyph that the font's character map gives it.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum ShapedScript {
18    /// The Arabic script: its letters and marks in the blocks Arabic, Arabic Supplement,
19    /// Arabic Extended-A and the two blocks of presentation forms.
20    Arabic,
21    /// The Devanagari script: its letters, vowel signs and marks in the blocks Devanagari and
22    /// Devanagari Extended, which the font's tables join into conjuncts, half forms and the
23    /// reph, and whose vowel signs they move before or over their consonants.
24    Devanagari,
25}
26
27impl ShapedScript {
28    /// The script of a character that goes through the layout tables, or nothing.
29    ///
30    /// The letters and marks of the Arabic blocks have the script, and so have the zero
31    /// width joiner and non-joiner, which change the form of the letters beside them. A
32    /// space, a digit (also an Arabic-Indic one), Arabic punctuation and every character of
33    /// another block have none: they end a stretch of shaped text, and a letter does not
34    /// join over them. The letters, vowel signs and marks of the Devanagari blocks have the
35    /// Devanagari script; its dandas, digits and abbreviation sign have none.
36    #[must_use]
37    pub fn of(ch: char) -> Option<Self> {
38        if matches!(ch, '\u{0900}'..='\u{0963}' | '\u{0971}'..='\u{097F}' | '\u{A8E0}'..='\u{A8FF}')
39        {
40            return Some(Self::Devanagari);
41        }
42        let arabic = match ch {
43            // Punctuation, number signs and digits of the Arabic block.
44            '\u{0600}'..='\u{060F}'
45            | '\u{061B}'..='\u{061F}'
46            | '\u{0660}'..='\u{066D}'
47            | '\u{06D4}'
48            | '\u{06DD}'
49            | '\u{06F0}'..='\u{06F9}' => false,
50            '\u{0610}'..='\u{06FF}'
51            | '\u{0750}'..='\u{077F}'
52            | '\u{08A0}'..='\u{08FF}'
53            | '\u{FB50}'..='\u{FDCF}'
54            | '\u{FDF0}'..='\u{FDFB}'
55            | '\u{FE70}'..='\u{FEFC}'
56            | '\u{200C}'
57            | '\u{200D}' => true,
58            _ => false,
59        };
60        arabic.then_some(Self::Arabic)
61    }
62
63    /// The direction in which text of the script reads.
64    #[must_use]
65    pub fn direction(self) -> ShapeDirection {
66        match self {
67            Self::Arabic => ShapeDirection::RightToLeft,
68            Self::Devanagari => ShapeDirection::LeftToRight,
69        }
70    }
71
72    /// The script for the shaping crate.
73    fn script(self) -> Script {
74        match self {
75            Self::Arabic => Script::ARABIC,
76            Self::Devanagari => Script::DEVANAGARI,
77        }
78    }
79}
80
81/// The direction in which a shaped text reads.
82#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
83pub enum ShapeDirection {
84    /// From left to right.
85    LeftToRight,
86    /// From right to left.
87    RightToLeft,
88}
89
90/// A text to shape with one face.
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub struct ShapeRequest<'a> {
93    /// The characters, in the order of the text.
94    pub text: &'a str,
95    /// The script of the characters.
96    pub script: ShapedScript,
97    /// The direction in which the text reads.
98    pub direction: ShapeDirection,
99    /// The language tag of the text, such as `fa-IR`, when it has one. A font can hold
100    /// other glyphs for a language.
101    pub language: Option<&'a str>,
102}
103
104/// One glyph of a shaped text, in font units.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub struct ShapedGlyph {
107    /// The glyph ID in the font.
108    pub glyph: u32,
109    /// How far the line goes on after the glyph.
110    pub advance: i32,
111    /// Where the glyph's origin lies from its place in the line: to the right and up.
112    pub offset: (i32, i32),
113    /// The byte index in [`ShapeRequest::text`] of the first character that the glyph
114    /// stands for. Glyphs of one group of characters share the index.
115    pub cluster: usize,
116}
117
118/// Why a text has no shaped glyphs.
119#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
120#[non_exhaustive]
121pub enum ShapeFailure {
122    /// The caller has no shaper.
123    NoShaper,
124    /// The database has no face of that ID.
125    UnknownFace,
126    /// The shaper refused the text or the face.
127    Refused,
128}
129
130impl fmt::Display for ShapeFailure {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.write_str(match self {
133            Self::NoShaper => "no shaper is available",
134            Self::UnknownFace => "the face is not in the font database",
135            Self::Refused => "the shaper refused the text or the face",
136        })
137    }
138}
139
140impl std::error::Error for ShapeFailure {}
141
142impl FontDb {
143    /// Returns the glyphs of a text by the layout tables of a face, in the order of the
144    /// text: the first glyph stands for the first characters, also in a text that reads
145    /// from right to left. The caller orders a line.
146    ///
147    /// # Errors
148    ///
149    /// Returns the cause when the face is unknown or when the shaper refuses the text or the
150    /// face. The caller then draws the characters with the glyphs of the font's character
151    /// map. A face without a `GSUB` and a `GPOS` table is no failure: the shaper then gives
152    /// an Arabic letter the glyph of its presentation-form character, when the font has it.
153    pub fn shape(
154        &self,
155        id: FontId,
156        request: &ShapeRequest<'_>,
157    ) -> Result<Vec<ShapedGlyph>, ShapeFailure> {
158        let font = self
159            .face(id)
160            .and_then(Face::font)
161            .ok_or(ShapeFailure::UnknownFace)?;
162        let font = ShaperFont::new(font);
163        let mut buffer = Buffer::new();
164        buffer.push_str(request.text);
165        buffer.set_direction(match request.direction {
166            ShapeDirection::LeftToRight => Direction::LeftToRight,
167            ShapeDirection::RightToLeft => Direction::RightToLeft,
168        });
169        buffer.set_script(Some(request.script.script()));
170        buffer.set_language(request.language.and_then(Language::new));
171        harfrust::shape(&font, &mut buffer, ShapeOptions::new())
172            .map_err(|_| ShapeFailure::Refused)?;
173        if !buffer.allocation_successful() {
174            return Err(ShapeFailure::Refused);
175        }
176        let mut glyphs: Vec<ShapedGlyph> = buffer
177            .glyph_infos()
178            .iter()
179            .zip(buffer.glyph_positions())
180            .map(|(info, position)| ShapedGlyph {
181                glyph: info.glyph_id,
182                advance: position.x_advance,
183                offset: (position.x_offset, position.y_offset),
184                cluster: usize::try_from(info.cluster).unwrap_or(usize::MAX),
185            })
186            .collect();
187        // The shaper gives a right-to-left text from the left of the line.
188        if request.direction == ShapeDirection::RightToLeft {
189            glyphs.reverse();
190        }
191        Ok(glyphs)
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::{ShapeDirection, ShapeFailure, ShapeRequest, ShapedScript};
198    use crate::tests::CARLITO;
199    use crate::{FontDb, FontId};
200
201    fn request(text: &str, direction: ShapeDirection) -> ShapeRequest<'_> {
202        ShapeRequest {
203            text,
204            script: ShapedScript::Arabic,
205            direction,
206            language: None,
207        }
208    }
209
210    /// Carlito with the tables of `tags` renamed, so that the font seems to lack them.
211    fn without_tables(tags: &[&[u8; 4]]) -> Vec<u8> {
212        let mut data = CARLITO.to_vec();
213        let count = usize::from(u16::from_be_bytes([data[4], data[5]]));
214        for record in 0..count {
215            let at = 12 + record * 16;
216            if tags.iter().any(|tag| data[at..at + 4] == tag[..]) {
217                data[at..at + 4].copy_from_slice(b"zzzz");
218            }
219        }
220        data
221    }
222
223    #[test]
224    fn only_letters_and_marks_of_the_arabic_and_devanagari_blocks_have_a_shaped_script() {
225        for ch in [
226            'ب', 'ـ', '\u{064E}', 'پ', '\u{FE8F}', '\u{200D}', '\u{200C}',
227        ] {
228            assert_eq!(ShapedScript::of(ch), Some(ShapedScript::Arabic), "{ch:?}");
229        }
230        for ch in [
231            ' ', '7', '٧', '۷', '،', '؟', 'a', 'א', '-', '\u{200F}', '।', '१',
232        ] {
233            assert_eq!(ShapedScript::of(ch), None, "{ch:?}");
234        }
235        for ch in ['क', '\u{094D}', '\u{093F}', '\u{0902}', 'ॐ', '\u{A8E0}'] {
236            assert_eq!(
237                ShapedScript::of(ch),
238                Some(ShapedScript::Devanagari),
239                "{ch:?}"
240            );
241        }
242    }
243
244    #[test]
245    fn gives_the_glyphs_in_the_order_of_the_text_in_both_directions() {
246        let mut db = FontDb::new();
247        let id = db.add_font(CARLITO.to_vec()).unwrap()[0];
248        let ids = ['o', 'x'].map(|ch| db.glyph_id(id, ch).unwrap());
249        for direction in [ShapeDirection::LeftToRight, ShapeDirection::RightToLeft] {
250            let glyphs = db.shape(id, &request("ox", direction)).unwrap();
251            assert_eq!(glyphs.iter().map(|g| g.glyph).collect::<Vec<_>>(), ids);
252            assert_eq!(glyphs.iter().map(|g| g.cluster).collect::<Vec<_>>(), [0, 1]);
253            assert!(glyphs.iter().all(|g| g.advance > 0 && g.offset == (0, 0)));
254        }
255    }
256
257    #[test]
258    fn shapes_a_face_without_layout_tables_by_its_character_map() {
259        let mut db = FontDb::new();
260        let bare = db.add_font(without_tables(&[b"GSUB", b"GPOS"])).unwrap()[0];
261        let ids = ['o', 'x'].map(|ch| db.glyph_id(bare, ch).unwrap());
262        let glyphs = db
263            .shape(bare, &request("ox", ShapeDirection::RightToLeft))
264            .unwrap();
265        assert_eq!(glyphs.iter().map(|g| g.glyph).collect::<Vec<_>>(), ids);
266    }
267
268    #[test]
269    fn says_why_a_text_has_no_shaped_glyphs() {
270        let db = FontDb::new();
271        let text = request("ox", ShapeDirection::LeftToRight);
272        let unknown = FontId::from_index(7);
273        assert_eq!(db.shape(unknown, &text), Err(ShapeFailure::UnknownFace));
274        assert_eq!(
275            ShapeFailure::UnknownFace.to_string(),
276            "the face is not in the font database"
277        );
278    }
279}