1use alloc::string::String;
24use alloc::vec::Vec;
25use font_parse::{FontRef, GlyphOutline, OutlinePoint};
26
27use crate::cmap::{self, Cmap, CmapSubtable};
28use crate::error::ModelError;
29use crate::font::{Font, Kerning, TableTag};
30use crate::glyph::{Glyph, GlyphId};
31use crate::metrics::{FontMetrics, Metrics};
32use crate::name::NameRecord;
33use crate::os2::Os2Metrics;
34use crate::outline::{Outline, Path};
35
36const OPAQUE_TAGS: [TableTag; 3] = [crate::TAG_GSUB, crate::TAG_GPOS, *b"GDEF"];
42
43#[allow(clippy::result_large_err)]
58pub fn from_sfnt(bytes: &[u8]) -> Result<Font, ModelError> {
59 let parsed = FontRef::new(bytes)?;
60 from_font_ref(&parsed)
61}
62
63#[allow(clippy::result_large_err)]
71pub fn from_font_ref(parsed: &FontRef<'_>) -> Result<Font, ModelError> {
72 let units_per_em = parsed.head()?.units_per_em()?;
73 let num_glyphs = parsed.num_glyphs();
74 if num_glyphs == 0 {
75 return Err(ModelError::UnknownGlyph {
76 glyph: GlyphId::NOTDEF,
77 glyph_count: 0,
78 });
79 }
80 let hmtx = parsed.hmtx().ok();
82 let mut glyphs = Vec::with_capacity(usize::from(num_glyphs));
83 for index in 0..num_glyphs {
84 let id = GlyphId::new(index);
85 let outline = parsed
86 .outline(font_parse::GlyphId::new(u32::from(index)))
87 .unwrap_or(None);
88 let outline = outline.map(to_outline).unwrap_or_default();
89 let (advance, lsb) = match &hmtx {
90 Some(h) => (
91 h.advance(index).unwrap_or(0),
92 h.left_side_bearing(index).unwrap_or(0),
93 ),
94 None => (0, 0),
95 };
96 glyphs.push(Glyph::new(id, advance, lsb, outline));
97 }
98 let cmap = load_cmap(parsed)?;
100 let mut metrics = FontMetrics::derive(&glyphs);
102 if let Ok(hhea) = parsed.hhea() {
103 if let (Ok(a), Ok(d), Ok(g)) = (hhea.ascender(), hhea.descender(), hhea.line_gap()) {
104 metrics.ascender = a;
105 metrics.descender = d;
106 metrics.line_gap = g;
107 }
108 }
109 if let Some(v) = load_vertical(parsed) {
110 metrics.vertical = Some(v);
111 }
112 let mut names = Vec::new();
114 if let Ok(table) = parsed.name() {
115 if let Ok(records) = table.records() {
116 for r in records {
117 names.push(NameRecord::with_locale(
118 r.name_id,
119 r.platform_id,
120 r.encoding_id,
121 r.language_id,
122 decode_name(&r),
123 ));
124 }
125 }
126 }
127 let os2 = parsed.os2().ok().map(|t| load_os2(&t));
129 let kerning = parsed
131 .table_by_tag(font_parse::Tag::new(b"kern"))
132 .map_or_else(Kerning::new, Kerning::from_kern_bytes);
133 let mut tables: Vec<(TableTag, Vec<u8>)> = Vec::new();
135 for tag in OPAQUE_TAGS {
136 if let Some(data) = raw_table(parsed, tag) {
137 tables.push((tag, data));
138 }
139 }
140 for (raw_tag, _checksum, _offset, _length) in parsed.table_directory() {
141 if tables.iter().any(|(t, _)| *t == raw_tag) {
142 continue;
143 }
144 if is_modelled(raw_tag) {
145 continue;
146 }
147 if let Some(data) = parsed.table_by_tag(font_parse::Tag::new(&raw_tag)) {
148 tables.push((raw_tag, data.to_vec()));
149 }
150 }
151 validate_references(&glyphs, &cmap, &kerning)?;
154 Ok(Font::from_parts(
155 units_per_em,
156 metrics,
157 glyphs,
158 cmap,
159 names,
160 os2,
161 kerning,
162 tables,
163 ))
164}
165
166fn raw_table(parsed: &FontRef<'_>, tag: TableTag) -> Option<Vec<u8>> {
168 parsed
169 .table_by_tag(font_parse::Tag::new(&tag))
170 .map(<[u8]>::to_vec)
171}
172
173fn is_modelled(tag: TableTag) -> bool {
175 const MODELLED: [TableTag; 10] = [
176 *b"cmap", *b"head", *b"hhea", *b"hmtx", *b"maxp", *b"name", *b"OS/2", *b"glyf", *b"loca",
177 *b"kern",
178 ];
179 MODELLED.contains(&tag)
180}
181
182fn load_cmap(parsed: &FontRef<'_>) -> Result<Cmap, ModelError> {
188 let Ok(table) = parsed.cmap() else {
189 return Ok(Cmap::format4());
190 };
191 let mut out = Cmap::new();
192 let records = table.records();
193 for (i, record) in records.iter().enumerate() {
194 if !record.is_unicode() {
195 continue;
196 }
197 let Ok(sub) = table.subtable(i) else { continue };
198 let format = match sub {
199 font_parse::CmapSubtable::Format4(_) => 4,
200 font_parse::CmapSubtable::Format12(_) => 12,
201 font_parse::CmapSubtable::Format0(_) | font_parse::CmapSubtable::Format6(_) => 4,
204 };
205 let entries = enumerate_subtable(&sub);
206 if entries.is_empty() {
207 continue;
208 }
209 out.subtables_mut()
210 .push(cmap::from_entries(&entries, format));
211 }
212 if out.subtables().is_empty() {
213 out.subtables_mut().push(CmapSubtable::empty_format4());
214 }
215 Ok(out)
216}
217
218fn enumerate_subtable(sub: &font_parse::CmapSubtable<'_>) -> Vec<(u32, GlyphId)> {
224 const MAX: u32 = 0x10_FFFF;
225 let mut out = Vec::new();
226 let mut cp = 0u32;
227 while cp <= MAX {
228 if !(0xD800..=0xDFFF).contains(&cp) {
229 if let Some(gid) = sub.lookup(cp) {
230 out.push((cp, GlyphId::new(gid)));
231 }
232 }
233 cp += 1;
234 }
235 out
236}
237
238fn decode_name(record: &font_parse::NameRecord<'_>) -> String {
240 record.decode()
241}
242
243fn load_os2(t: &font_parse::Os2Table<'_>) -> Os2Metrics {
245 let mut o = Os2Metrics::default();
246 if let Ok(v) = t.version() {
247 o.version = v;
248 }
249 if let Ok(v) = t.avg_char_width() {
250 o.avg_char_width = v;
251 }
252 if let Ok(v) = t.weight_class() {
253 o.weight_class = v;
254 }
255 if let Ok(v) = t.width_class() {
256 o.width_class = v;
257 }
258 if let Ok(v) = t.fs_type() {
259 o.fs_type = v;
260 }
261 if let Ok(p) = t.panose() {
262 for (slot, byte) in o.panose.iter_mut().zip(p.iter().take(10)) {
263 *slot = *byte;
264 }
265 }
266 if let Ok(r) = t.unicode_ranges() {
267 o.unicode_ranges = r;
268 }
269 if let Ok(v) = t.vendor_id() {
270 for (slot, byte) in o.vendor_id.iter_mut().zip(v.iter().take(4)) {
271 *slot = *byte;
272 }
273 }
274 if let Ok(v) = t.fs_selection() {
275 o.fs_selection = v;
276 }
277 if let Ok(v) = t.typo_ascender() {
278 o.typo_ascender = v;
279 }
280 if let Ok(v) = t.typo_descender() {
281 o.typo_descender = v;
282 }
283 if let Ok(v) = t.typo_line_gap() {
284 o.typo_line_gap = v;
285 }
286 if let Ok(v) = t.win_ascent() {
287 o.win_ascent = v;
288 }
289 if let Ok(v) = t.win_descent() {
290 o.win_descent = v;
291 }
292 if let Ok(v) = t.code_page_ranges() {
293 o.code_page_ranges = v;
294 }
295 if let Ok(v) = t.x_height() {
296 o.x_height = v;
297 }
298 if let Ok(v) = t.cap_height() {
299 o.cap_height = v;
300 }
301 o
302}
303
304fn load_vertical(parsed: &FontRef<'_>) -> Option<crate::VerticalMetrics> {
306 let vhea = parsed.table_by_tag(font_parse::Tag::new(b"vhea"))?;
309 parsed.table_by_tag(font_parse::Tag::new(b"vmtx"))?;
310 let be16 = |at: usize| -> i16 {
311 match (vhea.get(at), vhea.get(at + 1)) {
312 (Some(&a), Some(&b)) => i16::from_be_bytes([a, b]),
313 _ => 0,
314 }
315 };
316 Some(crate::VerticalMetrics {
317 ascender: be16(4),
318 descender: be16(6),
319 line_gap: be16(8),
320 advance_height_max: be16(10).max(0) as u16,
321 min_top_side_bearing: be16(12),
322 min_bottom_side_bearing: be16(14),
323 y_max_extent: be16(16),
324 })
325}
326
327fn validate_references(glyphs: &[Glyph], cmap: &Cmap, kerning: &Kerning) -> Result<(), ModelError> {
329 for cp in cmap.codepoints().iter() {
330 if let Some(gid) = cmap.lookup(*cp) {
331 if glyphs.get(gid.index()).is_none() {
332 return Err(ModelError::UnknownGlyph {
333 glyph: gid,
334 glyph_count: glyphs.len(),
335 });
336 }
337 }
338 }
339 for pair in kerning.iter() {
340 for gid in [pair.left, pair.right] {
341 if glyphs.get(gid.index()).is_none() {
342 return Err(ModelError::UnknownGlyph {
343 glyph: gid,
344 glyph_count: glyphs.len(),
345 });
346 }
347 }
348 }
349 Ok(())
350}
351
352#[must_use]
360pub fn to_outline(outline: GlyphOutline) -> Outline {
361 let mut out = Outline::new();
362 for contour in &outline.contours {
363 if let Some(path) = contour_to_path(&contour.points) {
364 out.push_contour(path);
365 }
366 }
367 out
368}
369
370fn contour_to_path(points: &[OutlinePoint]) -> Option<Path> {
372 let n = points.len();
373 if n == 0 {
374 return None;
375 }
376 if n == 1 {
377 let p = points.first()?;
378 let mut path = Path::starting_at(p.x, p.y);
379 path.close();
380 return Some(path);
381 }
382 let start_index = points.iter().position(|p| p.on_curve).unwrap_or(0);
385 let first = points.get(start_index)?;
387 let last = points.get((start_index + n - 1) % n)?;
388 let last_xy = (last.x, last.y);
389 let (sx, sy) = if first.on_curve {
390 (first.x, first.y)
391 } else if last.on_curve {
392 last_xy
393 } else {
394 midpoint(last_xy, (first.x, first.y))
395 };
396 let mut path = Path::starting_at(sx, sy);
397 let mut pending_control: Option<(f32, f32)> = None;
398 for k in 1..n {
403 let Some(p) = points.get((start_index + k) % n) else {
404 break;
405 };
406 if p.on_curve {
407 match pending_control.take() {
408 Some(c) => {
409 path.quad_to(c.0, c.1, p.x, p.y);
410 }
411 None => {
412 path.line_to(p.x, p.y);
413 }
414 }
415 } else {
416 if let Some(c) = pending_control {
417 let m = midpoint(c, (p.x, p.y));
420 path.quad_to(c.0, c.1, m.0, m.1);
421 }
422 pending_control = Some((p.x, p.y));
423 }
424 }
425 if let Some(c) = pending_control {
427 path.quad_to(c.0, c.1, sx, sy);
428 }
429 path.close();
430 Some(path)
431}
432
433fn midpoint(a: (f32, f32), b: (f32, f32)) -> (f32, f32) {
435 ((a.0 + b.0) * 0.5, (a.1 + b.1) * 0.5)
436}
437
438#[allow(clippy::result_large_err)]
445pub fn hmtx_rows(glyphs: &[Glyph]) -> Result<Vec<Metrics>, ModelError> {
446 glyphs.iter().map(Glyph::metrics).collect()
447}
448
449#[cfg(test)]
450mod tests {
451 #![allow(
452 clippy::unwrap_used,
453 clippy::expect_used,
454 clippy::indexing_slicing,
455 clippy::panic
456 )]
457 use super::{contour_to_path, from_sfnt, hmtx_rows, to_outline};
458 use crate::cmap::Cmap;
459 use crate::font::{TAG_GPOS, TAG_GSUB};
460 use crate::glyph::GlyphId;
461 use crate::outline::{Command, Outline, Winding};
462 use alloc::vec;
463 use alloc::vec::Vec;
464
465 fn pt(x: f32, y: f32, on: bool) -> font_parse::OutlinePoint {
469 font_parse::OutlinePoint { x, y, on_curve: on }
470 }
471
472 #[test]
473 fn rejects_non_font_bytes() {
474 assert!(from_sfnt(&[]).is_err());
475 assert!(
476 from_sfnt(&[0u8; 64]).is_err(),
477 "a zeroed buffer is not a font"
478 );
479 }
480
481 #[test]
482 fn contour_with_only_on_curve_points_becomes_lines() {
483 let path = contour_to_path(&[
484 pt(0.0, 0.0, true),
485 pt(100.0, 0.0, true),
486 pt(0.0, 100.0, true),
487 ])
488 .expect("contour");
489 assert_eq!(path.commands().len(), 4);
491 assert!(matches!(path.commands()[1], Command::LineTo(..)));
492 assert!(path.is_closed());
493 assert!((path.area() - 5000.0).abs() < 1e-2, "{}", path.area());
495 }
496
497 #[test]
498 fn contour_with_one_control_becomes_a_quad() {
499 let path = contour_to_path(&[
501 pt(0.0, 0.0, true),
502 pt(50.0, 100.0, false),
503 pt(100.0, 0.0, true),
504 pt(100.0, -100.0, true),
505 ])
506 .expect("contour");
507 assert!(matches!(path.commands()[1], Command::QuadTo(..)));
508 assert!(matches!(path.commands()[2], Command::LineTo(..)));
509 assert_eq!(path.commands().len(), 4, "MoveTo, quad, line, Close");
510 assert!(
513 (path.signed_area() + 8_333.333).abs() < 1e-2,
514 "area {}",
515 path.signed_area()
516 );
517 }
518
519 #[test]
520 fn two_controls_in_a_row_imply_an_on_curve_midpoint() {
521 let path = contour_to_path(&[
524 pt(0.0, 0.0, true),
525 pt(50.0, 100.0, false),
526 pt(50.0, -100.0, false),
527 pt(100.0, 0.0, true),
528 ])
529 .expect("contour");
530 let quads = path
531 .commands()
532 .iter()
533 .filter(|c| matches!(c, Command::QuadTo(..)))
534 .count();
535 assert_eq!(quads, 2, "implied midpoint split the segment");
536 assert!(matches!(
538 path.commands()[1],
539 Command::QuadTo(50.0, 100.0, 50.0, 0.0)
540 ));
541 }
542
543 #[test]
544 fn contour_starting_off_curve_starts_at_the_midpoint() {
545 let path = contour_to_path(&[
548 pt(50.0, 100.0, false),
549 pt(0.0, 0.0, true),
550 pt(-50.0, 100.0, false),
551 ])
552 .expect("contour");
553 assert_eq!(path.start_point(), (0.0, 0.0));
554 assert!(path.is_closed());
555 let all_off = contour_to_path(&[
558 pt(0.0, 0.0, false),
559 pt(100.0, 0.0, false),
560 pt(0.0, 100.0, false),
561 ])
562 .expect("contour");
563 assert_eq!(all_off.start_point(), (0.0, 50.0));
564 assert!(all_off.is_closed());
565 }
566
567 #[test]
568 fn degenerate_contours() {
569 assert!(contour_to_path(&[]).is_none());
570 let single = contour_to_path(&[pt(5.0, 5.0, true)]).expect("contour");
571 assert_eq!(single.len(), 2);
572 assert_eq!(single.winding(), Winding::Degenerate);
573 let same = contour_to_path(&[pt(1.0, 1.0, true), pt(1.0, 1.0, true), pt(1.0, 1.0, false)])
575 .expect("contour");
576 assert_eq!(same.area(), 0.0);
577 }
578
579 #[test]
580 fn to_outline_assembles_contours() {
581 let outline = font_parse::GlyphOutline {
582 contours: vec![
583 font_parse::Contour {
584 points: vec![
585 pt(0.0, 0.0, true),
586 pt(10.0, 0.0, true),
587 pt(10.0, 10.0, true),
588 ],
589 },
590 font_parse::Contour {
591 points: vec![
592 pt(20.0, 0.0, true),
593 pt(30.0, 0.0, true),
594 pt(30.0, 10.0, true),
595 ],
596 },
597 font_parse::Contour { points: Vec::new() },
598 ],
599 };
600 let o = to_outline(outline);
601 assert_eq!(o.len(), 2, "the empty contour was dropped");
602 assert!(o.validate(GlyphId::new(1)).is_ok());
603 assert_eq!(o.bbox().expect("bbox").max_x(), 30.0);
604 }
605
606 #[test]
607 fn hmtx_rows_follow_the_glyph_store() {
608 let glyphs = crate::glyph::stub_glyphs(&[0x41]);
609 let rows = hmtx_rows(&glyphs).expect("rows");
610 assert_eq!(rows.len(), glyphs.len());
611 assert_eq!(rows[1].advance_width(), 600);
612 }
613
614 #[test]
615 fn opaque_tag_helpers() {
616 assert_eq!(TAG_GSUB, *b"GSUB");
617 assert_eq!(TAG_GPOS, *b"GPOS");
618 assert!(super::is_modelled(*b"cmap"));
620 assert!(super::is_modelled(*b"head"));
621 assert!(!super::is_modelled(*b"GSUB"));
622 assert!(!super::is_modelled(*b"CFF "));
623 }
624
625 #[test]
626 fn empty_outline_default_is_blank() {
627 let o = Outline::new();
628 assert!(to_outline(font_parse::GlyphOutline {
629 contours: Vec::new()
630 })
631 .is_empty());
632 assert!(o.is_empty());
633 assert!(Cmap::new().lookup(0x41).is_none());
635 }
636}