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