1use std::fmt;
7
8use harfrust::{Buffer, Direction, Language, Script, ShapeOptions, ShaperFont};
9
10use crate::face::Face;
11use crate::{FontDb, FontId};
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum ShapedScript {
18 Arabic,
21 Devanagari,
25}
26
27impl ShapedScript {
28 #[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 '\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 #[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 fn script(self) -> Script {
74 match self {
75 Self::Arabic => Script::ARABIC,
76 Self::Devanagari => Script::DEVANAGARI,
77 }
78 }
79}
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
83pub enum ShapeDirection {
84 LeftToRight,
86 RightToLeft,
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub struct ShapeRequest<'a> {
93 pub text: &'a str,
95 pub script: ShapedScript,
97 pub direction: ShapeDirection,
99 pub language: Option<&'a str>,
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub struct ShapedGlyph {
107 pub glyph: u32,
109 pub advance: i32,
111 pub offset: (i32, i32),
113 pub cluster: usize,
116}
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
120#[non_exhaustive]
121pub enum ShapeFailure {
122 NoShaper,
124 UnknownFace,
126 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 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 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 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}