1use ab_glyph::Font;
4
5mod config;
6mod raster;
7#[cfg(test)]
8mod tests;
9pub use config::{
10 FontBudget, FontBudgetResource, FontError, TextDirection, TextLayoutBudget, TextStyle,
11};
12use config::{check, reserve};
13pub use raster::RasterizedGlyph;
14
15#[derive(Debug, Clone)]
23pub struct FontFace {
24 font: std::sync::Arc<ab_glyph::FontVec>,
25 source_capacity: usize,
26 glyph_count: usize,
27}
28
29impl FontFace {
30 pub fn from_bytes(bytes: Vec<u8>, budget: FontBudget) -> Result<Self, FontError> {
33 check(
34 FontBudgetResource::FontBytes,
35 bytes.capacity(),
36 budget.max_font_bytes(),
37 )?;
38 let face =
39 rustybuzz::ttf_parser::Face::parse(&bytes, 0).map_err(|_| FontError::InvalidFont)?;
40 let tables = face.tables();
41 if tables.glyf.is_none() && tables.cff.is_none() && tables.cff2.is_none() {
42 return Err(FontError::InvalidFont);
43 }
44 let glyph_count = usize::from(face.number_of_glyphs());
45 check(
46 FontBudgetResource::FontGlyphs,
47 glyph_count,
48 budget.max_font_glyphs(),
49 )?;
50 if face.units_per_em() == 0 || face.ascender() <= face.descender() {
51 return Err(FontError::InvalidFont);
52 }
53 let source_capacity = bytes.capacity();
54 let font = ab_glyph::FontVec::try_from_vec(bytes).map_err(|_| FontError::InvalidFont)?;
55 Ok(Self {
56 font: std::sync::Arc::new(font),
57 source_capacity,
58 glyph_count,
59 })
60 }
61
62 pub fn font_data(&self) -> &[u8] {
64 self.font.as_slice()
65 }
66 pub const fn allocation_bytes(&self) -> usize {
69 self.source_capacity
70 }
71 pub const fn glyph_count(&self) -> usize {
73 self.glyph_count
74 }
75
76 pub fn shape_line(
84 &self,
85 text: &str,
86 style: &TextStyle,
87 budget: &TextLayoutBudget,
88 ) -> Result<ShapedLine, FontError> {
89 check(
90 FontBudgetResource::TextBytes,
91 text.len(),
92 budget.max_text_bytes().min(u32::MAX as usize),
93 )?;
94 for (byte_index, character) in text.char_indices() {
95 if character.is_control() || matches!(character, '\u{2028}' | '\u{2029}') {
96 return Err(FontError::UnsupportedText { byte_index });
97 }
98 }
99 let face =
100 rustybuzz::Face::from_slice(self.font.as_slice(), 0).ok_or(FontError::InvalidFont)?;
101 let factor = f64::from(style.logical_em_size().get()) / f64::from(face.units_per_em());
102 let ascent = represent(f64::from(face.ascender()) * factor)?;
103 let descent = represent(f64::from(face.descender()) * factor)?;
104 let line_height = represent(
105 (f64::from(face.ascender()) - f64::from(face.descender()) + f64::from(face.line_gap()))
106 * factor,
107 )?;
108 if line_height <= 0.0 {
109 return Err(FontError::InvalidFont);
110 }
111 let mut input = rustybuzz::UnicodeBuffer::new();
112 input.push_str(text);
113 match style.direction() {
114 TextDirection::Auto => {}
115 TextDirection::Ltr => input.set_direction(rustybuzz::Direction::LeftToRight),
116 TextDirection::Rtl => input.set_direction(rustybuzz::Direction::RightToLeft),
117 }
118 input.guess_segment_properties();
119 let output = rustybuzz::shape(&face, &[], input);
120 check(
121 FontBudgetResource::ShapedGlyphs,
122 output.len(),
123 budget.max_shaped_glyphs(),
124 )?;
125 let mut glyphs = Vec::new();
126 reserve(&mut glyphs, output.len())?;
127 let mut pen_x = 0.0f64;
128 let mut pen_y = 0.0f64;
129 for (information, position) in output.glyph_infos().iter().zip(output.glyph_positions()) {
130 if information.glyph_id == 0 {
131 return Err(FontError::MissingGlyph {
132 byte_index: information.cluster as usize,
133 });
134 }
135 let glyph_id =
136 u16::try_from(information.glyph_id).map_err(|_| FontError::InvalidGeometry)?;
137 glyphs.push(ShapedGlyph {
138 glyph_id,
139 logical_x: represent((pen_x + f64::from(position.x_offset)) * factor)?,
140 logical_y: represent(-(pen_y + f64::from(position.y_offset)) * factor)?,
141 cluster: information.cluster as usize,
142 });
143 pen_x += f64::from(position.x_advance);
144 pen_y += f64::from(position.y_advance);
145 }
146 Ok(ShapedLine {
147 glyphs,
148 advance: represent(pen_x * factor)?,
149 ascent,
150 descent,
151 line_height,
152 })
153 }
154
155 pub fn rasterize_glyph(
161 &self,
162 glyph_id: u16,
163 style: &TextStyle,
164 budget: &TextLayoutBudget,
165 ) -> Result<RasterizedGlyph, FontError> {
166 raster::rasterize(self, glyph_id, style, budget)
167 }
168}
169
170#[derive(Debug, Clone, Copy, PartialEq)]
172pub struct ShapedGlyph {
173 glyph_id: u16,
174 logical_x: f32,
175 logical_y: f32,
176 cluster: usize,
177}
178
179impl ShapedGlyph {
180 pub const fn glyph_id(self) -> u16 {
182 self.glyph_id
183 }
184 pub const fn logical_x(self) -> f32 {
186 self.logical_x
187 }
188 pub const fn logical_y(self) -> f32 {
190 self.logical_y
191 }
192 pub const fn cluster(self) -> usize {
194 self.cluster
195 }
196}
197
198#[derive(Debug)]
200pub struct ShapedLine {
201 glyphs: Vec<ShapedGlyph>,
202 advance: f32,
203 ascent: f32,
204 descent: f32,
205 line_height: f32,
206}
207
208impl ShapedLine {
209 pub fn glyphs(&self) -> &[ShapedGlyph] {
211 &self.glyphs
212 }
213 pub const fn advance(&self) -> f32 {
215 self.advance
216 }
217 pub const fn ascent(&self) -> f32 {
219 self.ascent
220 }
221 pub const fn descent(&self) -> f32 {
223 self.descent
224 }
225 pub const fn line_height(&self) -> f32 {
227 self.line_height
228 }
229 pub fn allocation_bytes(&self) -> usize {
231 self.glyphs
232 .capacity()
233 .saturating_mul(std::mem::size_of::<ShapedGlyph>())
234 }
235}
236
237fn represent(value: f64) -> Result<f32, FontError> {
238 let result = value as f32;
239 if result.is_finite() {
240 Ok(result)
241 } else {
242 Err(FontError::InvalidGeometry)
243 }
244}