1use std::cell::RefCell;
14use std::collections::BTreeMap;
15use std::rc::Rc;
16
17use pdf2::Encoding;
18
19use crate::geom::Point;
20
21#[derive(Debug, Default)]
29pub struct Cache {
30 cmap: BTreeMap<char, Option<u16>>,
32 glyphs: BTreeMap<u16, Option<Glyph>>,
34}
35
36pub type GlyphCache = Rc<RefCell<Cache>>;
38
39#[derive(Debug, Clone, Default, PartialEq)]
42pub struct Glyph {
43 pub contours: Vec<Vec<Point>>,
45 pub advance: f64,
47}
48
49#[derive(Debug, Clone)]
51pub enum Font {
52 Builtin {
55 encoding: Encoding,
57 },
58 Type1 {
63 encoding: Encoding,
65 program: Rc<crate::type1::Program>,
67 names: std::collections::HashMap<char, Vec<u8>>,
69 },
70 Cff {
74 encoding: Encoding,
76 data: Vec<u8>,
78 cid_to_gid: Vec<(u16, u16)>,
81 names: std::collections::HashMap<char, u16>,
86 cache: GlyphCache,
88 },
89 TrueType {
91 encoding: Encoding,
93 data: Vec<u8>,
96 has_cmap: bool,
99 cache: GlyphCache,
101 },
102}
103
104impl Font {
105 pub fn builtin(encoding: Encoding) -> Self {
107 Self::Builtin { encoding }
108 }
109
110 pub fn cff(encoding: Encoding, data: Vec<u8>) -> Option<Self> {
115 let wrapped = data.starts_with(b"OTTO");
116 let table: Vec<u8> = if wrapped {
117 cff_table_of_sfnt(&data)?.to_vec()
118 } else {
119 data.clone()
120 };
121 let (charset_at, glyphs) = cff_layout(&table)?;
122 let cid_to_gid = if top_dict_declares_ros(&table) {
125 cff_charset(&table, charset_at, glyphs)
126 } else {
127 Vec::new()
128 };
129 let program = if wrapped {
130 data
131 } else {
132 wrap_cff(&table, glyphs)?
133 };
134 let face = ttf_parser::Face::parse(&program, 0).ok()?;
137 let names = if cid_to_gid.is_empty() {
138 glyph_names(&face)
139 } else {
140 std::collections::HashMap::new()
141 };
142 Some(Self::Cff {
143 encoding,
144 data: program,
145 cid_to_gid,
146 names,
147 cache: GlyphCache::default(),
148 })
149 }
150
151 pub fn type1(encoding: Encoding, program: crate::type1::Program) -> Option<Self> {
156 if !program.is_usable() {
157 return None;
158 }
159 let mut names = std::collections::HashMap::new();
160 for name in program.names() {
161 if let Some(character) = pdf2::encoding::glyph_name_character(name) {
162 names.entry(character).or_insert_with(|| name.to_vec());
163 }
164 }
165 Some(Self::Type1 {
166 encoding,
167 program: Rc::new(program),
168 names,
169 })
170 }
171
172 pub fn true_type(encoding: Encoding, data: Vec<u8>) -> Option<Self> {
174 let face = ttf_parser::Face::parse(&data, 0).ok()?;
175 if face.units_per_em() == 0 {
176 return None;
177 }
178 let has_cmap = face.tables().cmap.is_some();
179 Some(Self::TrueType {
180 encoding,
181 data,
182 has_cmap,
183 cache: GlyphCache::default(),
184 })
185 }
186
187 pub fn glyph(&self, code: u8) -> Option<Glyph> {
197 match self {
198 Self::Builtin { encoding } => builtin_glyph(encoding.character(code)?),
199 Self::Type1 {
200 encoding,
201 program,
202 names,
203 } => {
204 let character = encoding.character(code)?;
205 program.glyph(names.get(&character)?)
206 }
207 Self::TrueType {
208 encoding,
209 data,
210 cache,
211 ..
212 } => {
213 let character = encoding.character(code)?;
214 cached_glyph(data, cache, glyph_id(data, cache, character)?)
215 }
216 Self::Cff {
217 encoding,
218 data,
219 names,
220 cache,
221 ..
222 } => {
223 let character = encoding.character(code)?;
224 let id = if names.is_empty() {
228 glyph_id(data, cache, character)?
229 } else {
230 ttf_parser::GlyphId(*names.get(&character)?)
231 };
232 cached_glyph(data, cache, id)
233 }
234 }
235 }
236
237 pub fn has_glyph_names(&self) -> bool {
240 match self {
241 Self::Type1 { names, .. } => !names.is_empty(),
242 Self::Cff { names, .. } => !names.is_empty(),
243 Self::TrueType { has_cmap, .. } => *has_cmap,
244 Self::Builtin { .. } => false,
245 }
246 }
247
248 pub fn has_character_map(&self) -> bool {
253 match self {
254 Self::Builtin { .. } | Self::Cff { .. } | Self::Type1 { .. } => true,
255 Self::TrueType { has_cmap, .. } => *has_cmap,
256 }
257 }
258
259 pub fn advance(&self, code: u8) -> f64 {
261 self.glyph(code)
262 .map_or(BUILTIN_ADVANCE, |glyph| glyph.advance)
263 }
264
265 pub fn glyph_by_id(&self, id: u16) -> Option<Glyph> {
270 match self {
271 Self::Builtin { .. } => None,
272 Self::TrueType { data, cache, .. } => {
273 cached_glyph(data, cache, ttf_parser::GlyphId(id))
274 }
275 Self::Type1 { .. } => None,
276 Self::Cff {
277 data,
278 cid_to_gid,
279 cache,
280 ..
281 } => {
282 let glyph = cid_to_gid
285 .iter()
286 .find(|(cid, _)| *cid == id)
287 .map_or(id, |(_, gid)| *gid);
288 cached_glyph(data, cache, ttf_parser::GlyphId(glyph))
289 }
290 }
291 }
292}
293
294fn glyph_names(face: &ttf_parser::Face<'_>) -> std::collections::HashMap<char, u16> {
300 let mut map = std::collections::HashMap::new();
301 for id in 0..face.number_of_glyphs() {
302 let Some(name) = face.glyph_name(ttf_parser::GlyphId(id)) else {
303 continue;
304 };
305 if let Some(character) = pdf2::encoding::glyph_name_character(name.as_bytes()) {
306 map.entry(character).or_insert(id);
307 }
308 }
309 map
310}
311
312fn glyph_id(data: &[u8], cache: &GlyphCache, character: char) -> Option<ttf_parser::GlyphId> {
314 if let Some(cached) = cache.borrow().cmap.get(&character) {
315 return cached.map(ttf_parser::GlyphId);
316 }
317 let face = ttf_parser::Face::parse(data, 0).ok()?;
318 let found = face.glyph_index(character).map(|id| id.0);
319 cache.borrow_mut().cmap.insert(character, found);
320 found.map(ttf_parser::GlyphId)
321}
322
323fn cached_glyph(data: &[u8], cache: &GlyphCache, id: ttf_parser::GlyphId) -> Option<Glyph> {
325 if let Some(cached) = cache.borrow().glyphs.get(&id.0) {
326 return cached.clone();
327 }
328 let glyph = glyph_from_face(data, id);
329 cache.borrow_mut().glyphs.insert(id.0, glyph.clone());
330 glyph
331}
332
333fn wrap_cff(cff: &[u8], glyphs: u16) -> Option<Vec<u8>> {
341 let mut head = [0_u8; 54];
342 head[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
343 head[4..8].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
344 head[12..16].copy_from_slice(&0x5F0F_3CF5_u32.to_be_bytes());
345 head[18..20].copy_from_slice(&1000_u16.to_be_bytes());
346 let mut hhea = [0_u8; 36];
347 hhea[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
348 hhea[34..36].copy_from_slice(&glyphs.to_be_bytes());
349 let mut maxp = [0_u8; 6];
350 maxp[0..4].copy_from_slice(&0x0000_5000_u32.to_be_bytes());
351 maxp[4..6].copy_from_slice(&glyphs.to_be_bytes());
352 let hmtx = vec![0_u8; usize::from(glyphs) * 4];
353
354 let tables: [(&[u8; 4], &[u8]); 5] = [
355 (b"CFF ", cff),
356 (b"head", &head),
357 (b"hhea", &hhea),
358 (b"hmtx", &hmtx),
359 (b"maxp", &maxp),
360 ];
361 let count = u16::try_from(tables.len()).ok()?;
362 let mut out = Vec::with_capacity(cff.len() + 256);
363 out.extend_from_slice(&0x4F54_544F_u32.to_be_bytes());
364 out.extend_from_slice(&count.to_be_bytes());
365 let pow2 = 1_u32 << u32::from(count).ilog2();
366 #[allow(clippy::cast_possible_truncation)]
367 let search_range = pow2 * 16;
368 out.extend_from_slice(&u16::try_from(search_range).ok()?.to_be_bytes());
369 #[allow(clippy::cast_possible_truncation)]
370 let entry_selector = count.trailing_zeros() as u16;
371 out.extend_from_slice(&entry_selector.to_be_bytes());
372 #[allow(clippy::cast_possible_truncation)]
373 let range_shift = (u32::from(count) * 16).saturating_sub(search_range) as u16;
374 out.extend_from_slice(&range_shift.to_be_bytes());
375
376 let mut offset = 12 + usize::from(count) * 16;
377 let mut body: Vec<u8> = Vec::with_capacity(cff.len() + 128);
378 for (tag, data) in &tables {
379 let mut table = data.to_vec();
380 while !table.len().is_multiple_of(4) {
381 table.push(0);
382 }
383 out.extend_from_slice(*tag);
384 out.extend_from_slice(&0_u32.to_be_bytes());
385 out.extend_from_slice(&u32::try_from(offset).ok()?.to_be_bytes());
386 out.extend_from_slice(&u32::try_from(data.len()).ok()?.to_be_bytes());
387 offset += table.len();
388 body.extend_from_slice(&table);
389 }
390 out.extend_from_slice(&body);
391 Some(out)
392}
393
394fn cff_table_of_sfnt(data: &[u8]) -> Option<&[u8]> {
396 let count = usize::from(u16::from_be_bytes([*data.get(4)?, *data.get(5)?]));
397 for index in 0..count {
398 let at = 12 + index * 16;
399 if data.get(at..at + 4)? == b"CFF " {
400 let offset = u32::from_be_bytes([
401 *data.get(at + 8)?,
402 *data.get(at + 9)?,
403 *data.get(at + 10)?,
404 *data.get(at + 11)?,
405 ]);
406 let length = u32::from_be_bytes([
407 *data.get(at + 12)?,
408 *data.get(at + 13)?,
409 *data.get(at + 14)?,
410 *data.get(at + 15)?,
411 ]);
412 let start = usize::try_from(offset).ok()?;
413 let end = start.checked_add(usize::try_from(length).ok()?)?;
414 return data.get(start..end);
415 }
416 }
417 None
418}
419
420fn cff_layout(cff: &[u8]) -> Option<(usize, u16)> {
422 let header_size = usize::from(*cff.get(2)?);
423 let (_, after_name) = cff_index(cff, header_size)?;
424 let (top_count, after_top) = cff_index(cff, after_name)?;
425 if top_count == 0 {
426 return None;
427 }
428 let (_, after_strings) = cff_index(cff, after_top)?;
429 let (_, after_global_subrs) = cff_index(cff, after_strings)?;
430 let _ = after_global_subrs;
431 let top_dict = cff_index_item(cff, after_name, 0)?;
432 let charstrings_at = top_dict_operator(top_dict, 17)?;
433 let (glyphs, _) = cff_index(cff, charstrings_at)?;
434 let charset_at = top_dict_operator(top_dict, 15).unwrap_or(0);
435 Some((charset_at, u16::try_from(glyphs).ok()?))
436}
437
438fn top_dict_declares_ros(cff: &[u8]) -> bool {
441 let Some(header_size) = cff.get(2).map(|size| usize::from(*size)) else {
442 return false;
443 };
444 let Some((_, after_name)) = cff_index(cff, header_size) else {
445 return false;
446 };
447 let Some(dict) = cff_index_item(cff, after_name, 0) else {
448 return false;
449 };
450 dict.windows(2).any(|window| window == [12, 30])
452}
453
454fn cff_charset(cff: &[u8], at: usize, glyphs: u16) -> Vec<(u16, u16)> {
460 let mut pairs = Vec::new();
461 if at < 3 {
462 return pairs;
463 }
464 let Some(&format) = cff.get(at) else {
465 return pairs;
466 };
467 let mut index = at + 1;
468 let mut gid = 1u16;
469 match format {
470 0 => {
471 while gid < glyphs {
472 let cid = cff
473 .get(index..index + 2)
474 .map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]));
475 let Some(cid) = cid else { break };
476 pairs.push((cid, gid));
477 gid += 1;
478 index += 2;
479 }
480 }
481 1 | 2 => {
482 while gid < glyphs {
483 let width = if format == 1 { 1 } else { 2 };
484 let first = cff
485 .get(index..index + 2)
486 .map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]));
487 let left = cff.get(index + 2..index + 2 + width).map(|bytes| {
488 if width == 1 {
489 u16::from(bytes[0])
490 } else {
491 u16::from_be_bytes([bytes[0], bytes[1]])
492 }
493 });
494 let (Some(first), Some(left)) = (first, left) else {
495 break;
496 };
497 for offset in 0..=left {
498 if gid >= glyphs {
499 break;
500 }
501 pairs.push((first.wrapping_add(offset), gid));
502 gid += 1;
503 }
504 index += 2 + width;
505 }
506 }
507 _ => {}
508 }
509 pairs
510}
511
512fn cff_index(data: &[u8], at: usize) -> Option<(usize, usize)> {
514 let count = usize::from(u16::from_be_bytes([*data.get(at)?, *data.get(at + 1)?]));
515 if count == 0 {
516 return Some((0, at + 2));
517 }
518 let off_size = usize::from(*data.get(at + 2)?);
519 if !(1..=4).contains(&off_size) {
520 return None;
521 }
522 let offsets_at = at + 3;
523 let data_at = offsets_at + (count + 1) * off_size;
524 let mut last = 0;
525 for index in 0..off_size {
526 last = (last << 8) | usize::from(*data.get(offsets_at + count * off_size + index)?);
527 }
528 Some((count, data_at + last.saturating_sub(1)))
529}
530
531fn cff_index_item(data: &[u8], at: usize, item: usize) -> Option<&[u8]> {
533 let count = usize::from(u16::from_be_bytes([*data.get(at)?, *data.get(at + 1)?]));
534 if item >= count {
535 return None;
536 }
537 let off_size = usize::from(*data.get(at + 2)?);
538 let offsets_at = at + 3;
539 let data_at = offsets_at + (count + 1) * off_size;
540 let read = |position: usize| -> Option<usize> {
541 let base = offsets_at + position * off_size;
542 let mut value = 0;
543 for index in 0..off_size {
544 value = (value << 8) | usize::from(*data.get(base + index)?);
545 }
546 Some(value)
547 };
548 let start = read(item)?;
549 let end = read(item + 1)?;
550 data.get(data_at + start - 1..data_at + end - 1)
551}
552
553fn top_dict_operator(dict: &[u8], operator: u8) -> Option<usize> {
555 let mut operands: Vec<f64> = Vec::new();
556 let mut index = 0;
557 while index < dict.len() {
558 let byte = *dict.get(index)?;
559 index += 1;
560 match byte {
561 28 => {
562 let value = i16::from_be_bytes([*dict.get(index)?, *dict.get(index + 1)?]);
563 operands.push(f64::from(value));
564 index += 2;
565 }
566 29 => {
567 let mut bytes = [0_u8; 4];
568 for (offset, slot) in bytes.iter_mut().enumerate() {
569 *slot = *dict.get(index + offset)?;
570 }
571 operands.push(f64::from(i32::from_be_bytes(bytes)));
572 index += 4;
573 }
574 32..=246 => operands.push(f64::from(byte) - 139.0),
575 247..=250 => {
576 let next = f64::from(*dict.get(index)?);
577 operands.push((f64::from(byte) - 247.0) * 256.0 + next + 108.0);
578 index += 1;
579 }
580 251..=254 => {
581 let next = f64::from(*dict.get(index)?);
582 operands.push(-(f64::from(byte) - 251.0) * 256.0 - next - 108.0);
583 index += 1;
584 }
585 30 => {
586 while index < dict.len() {
589 let nibble = dict[index];
590 index += 1;
591 if nibble & 0x0F == 0x0F || nibble >> 4 == 0x0F {
592 break;
593 }
594 }
595 operands.push(f64::NAN);
596 }
597 0..=21 => {
598 if byte == 12 {
599 index += 1;
600 }
601 if byte == operator {
602 if let Some(value) = operands.last() {
603 if value.is_finite() && *value >= 0.0 {
604 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
605 return Some(*value as usize);
606 }
607 }
608 return None;
609 }
610 operands.clear();
611 }
612 _ => operands.clear(),
613 }
614 }
615 None
616}
617
618fn glyph_from_face(data: &[u8], glyph_id: ttf_parser::GlyphId) -> Option<Glyph> {
620 let face = ttf_parser::Face::parse(data, 0).ok()?;
621 let units = f64::from(face.units_per_em());
622 let mut builder = OutlineBuilder::new(units);
623 face.outline_glyph(glyph_id, &mut builder)?;
624 let advance = f64::from(face.glyph_hor_advance(glyph_id).unwrap_or(0)) / units;
625 Some(Glyph {
626 contours: builder.contours,
627 advance,
628 })
629}
630
631const BUILTIN_ADVANCE: f64 = 6.0 / 9.0;
632const BUILTIN_CELL: f64 = 1.0 / 9.0;
633const BUILTIN_WIDTH: u8 = 5;
634const BUILTIN_HEIGHT: u8 = 7;
635
636fn builtin_glyph(character: char) -> Option<Glyph> {
639 let code = u8::try_from(u32::from(character)).ok()?;
640 if character == ' ' {
641 return Some(Glyph {
642 contours: Vec::new(),
643 advance: BUILTIN_ADVANCE,
644 });
645 }
646 if let Some(rows) = glyph_rows(code) {
647 return Some(Glyph {
648 contours: rows_to_contours(&rows),
649 advance: BUILTIN_ADVANCE,
650 });
651 }
652 if character == '\u{2022}' {
653 return Some(Glyph {
654 contours: rows_to_contours(&[0, 0, 0b00100, 0b01110, 0b00100, 0, 0]),
655 advance: BUILTIN_ADVANCE,
656 });
657 }
658 if let Some((base, accent)) = decompose(character) {
661 let rows = glyph_rows(u8::try_from(u32::from(base)).unwrap_or(b'?'))
662 .or_else(|| upper(base).and_then(|upper| glyph_rows(upper as u8)))
663 .unwrap_or_else(notdef_rows);
664 let mut contours = rows_to_contours(&rows);
665 contours.extend(
666 accent
667 .cells()
668 .iter()
669 .map(|&(column, layer)| mark_cell(column, layer)),
670 );
671 return Some(Glyph {
672 contours,
673 advance: BUILTIN_ADVANCE,
674 });
675 }
676 if character == '\u{00F8}' || character == '\u{00D8}' {
677 let mut contours = rows_to_contours(&glyph_rows(b'O').unwrap_or_else(notdef_rows));
680 contours.extend(
681 [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)]
682 .iter()
683 .map(|&(column, layer)| mark_cell(column, layer)),
684 );
685 return Some(Glyph {
686 contours,
687 advance: BUILTIN_ADVANCE,
688 });
689 }
690 let rows = upper(character)
691 .and_then(|upper| glyph_rows(upper as u8))
692 .unwrap_or_else(notdef_rows);
693 Some(Glyph {
694 contours: rows_to_contours(&rows),
695 advance: BUILTIN_ADVANCE,
696 })
697}
698
699#[derive(Clone, Copy, PartialEq, Eq, Debug)]
702enum Accent {
703 Acute,
704 Grave,
705 Circumflex,
706 Diaeresis,
707 Tilde,
708 Ring,
709 Cedilla,
710}
711
712impl Accent {
713 fn cells(self) -> &'static [(u8, i8)] {
717 match self {
718 Self::Acute => &[(2, 0), (3, 0), (3, 1)],
719 Self::Grave => &[(2, 1), (3, 1), (3, 0)],
720 Self::Circumflex => &[(1, 0), (2, 1), (3, 0)],
721 Self::Diaeresis => &[(1, 1), (3, 1)],
722 Self::Tilde => &[(1, 1), (2, 0), (3, 1)],
723 Self::Ring => &[(1, 0), (2, 1), (3, 0), (2, 0)],
724 Self::Cedilla => &[(2, -1), (3, -1), (3, -2)],
725 }
726 }
727}
728
729fn mark_cell(column: u8, layer: i8) -> Vec<Point> {
731 let x0 = f64::from(column) * BUILTIN_CELL;
732 let x1 = x0 + BUILTIN_CELL;
733 let (bottom, top) = if layer < 0 {
734 (
735 f64::from(layer) * BUILTIN_CELL,
736 f64::from(layer + 1) * BUILTIN_CELL,
737 )
738 } else {
739 (
740 f64::from(BUILTIN_HEIGHT + layer as u8) * BUILTIN_CELL,
741 f64::from(BUILTIN_HEIGHT + layer as u8 + 1) * BUILTIN_CELL,
742 )
743 };
744 vec![
745 Point::new(x0, bottom),
746 Point::new(x1, bottom),
747 Point::new(x1, top),
748 Point::new(x0, top),
749 ]
750}
751
752fn decompose(character: char) -> Option<(char, Accent)> {
755 let (base, accent) = match character {
756 'á' | 'Á' => ('a', Accent::Acute),
757 'é' | 'É' => ('e', Accent::Acute),
758 'í' | 'Í' => ('i', Accent::Acute),
759 'ó' | 'Ó' => ('o', Accent::Acute),
760 'ú' | 'Ú' => ('u', Accent::Acute),
761 'ý' | 'Ý' => ('y', Accent::Acute),
762 'à' | 'À' => ('a', Accent::Grave),
763 'è' | 'È' => ('e', Accent::Grave),
764 'ì' | 'Ì' => ('i', Accent::Grave),
765 'ò' | 'Ò' => ('o', Accent::Grave),
766 'ù' | 'Ù' => ('u', Accent::Grave),
767 'â' | 'Â' => ('a', Accent::Circumflex),
768 'ê' | 'Ê' => ('e', Accent::Circumflex),
769 'î' | 'Î' => ('i', Accent::Circumflex),
770 'ô' | 'Ô' => ('o', Accent::Circumflex),
771 'û' | 'Û' => ('u', Accent::Circumflex),
772 'ä' | 'Ä' => ('a', Accent::Diaeresis),
773 'ë' | 'Ë' => ('e', Accent::Diaeresis),
774 'ï' | 'Ï' => ('i', Accent::Diaeresis),
775 'ö' | 'Ö' => ('o', Accent::Diaeresis),
776 'ü' | 'Ü' => ('u', Accent::Diaeresis),
777 'ÿ' | 'Ÿ' => ('y', Accent::Diaeresis),
778 'ã' | 'Ã' => ('a', Accent::Tilde),
779 'õ' | 'Õ' => ('o', Accent::Tilde),
780 'ñ' | 'Ñ' => ('n', Accent::Tilde),
781 'å' | 'Å' => ('a', Accent::Ring),
782 'ç' | 'Ç' => ('c', Accent::Cedilla),
783 _ => return None,
784 };
785 Some((base, accent))
786}
787
788fn upper(character: char) -> Option<char> {
789 character
790 .to_uppercase()
791 .next()
792 .filter(|upper| *upper != character)
793}
794
795fn notdef_rows() -> [u8; BUILTIN_HEIGHT as usize] {
796 [
797 0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111,
798 ]
799}
800
801fn rows_to_contours(rows: &[u8; BUILTIN_HEIGHT as usize]) -> Vec<Vec<Point>> {
802 let mut contours = Vec::new();
803 for (row, bits) in rows.iter().enumerate() {
804 for column in 0..BUILTIN_WIDTH {
805 let mask = 1_u8 << (BUILTIN_WIDTH - 1 - column);
806 if bits & mask == 0 {
807 continue;
808 }
809 let x0 = f64::from(column) * BUILTIN_CELL;
810 let x1 = x0 + BUILTIN_CELL;
811 let top = f64::from(BUILTIN_HEIGHT - 1 - row as u8) * BUILTIN_CELL;
812 let bottom = top + BUILTIN_CELL;
813 contours.push(vec![
814 Point::new(x0, bottom),
815 Point::new(x1, bottom),
816 Point::new(x1, top),
817 Point::new(x0, top),
818 ]);
819 }
820 }
821 contours
822}
823
824fn glyph_rows(code: u8) -> Option<[u8; 7]> {
825 let rows = match code {
826 b'A' => [
827 0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
828 ],
829 b'B' => [
830 0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110,
831 ],
832 b'C' => [
833 0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
834 ],
835 b'D' => [
836 0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
837 ],
838 b'E' => [
839 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
840 ],
841 b'F' => [
842 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000,
843 ],
844 b'G' => [
845 0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110,
846 ],
847 b'H' => [
848 0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
849 ],
850 b'I' => [
851 0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
852 ],
853 b'J' => [
854 0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100,
855 ],
856 b'K' => [
857 0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001,
858 ],
859 b'L' => [
860 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
861 ],
862 b'M' => [
863 0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
864 ],
865 b'N' => [
866 0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
867 ],
868 b'O' => [
869 0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
870 ],
871 b'P' => [
872 0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
873 ],
874 b'Q' => [
875 0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101,
876 ],
877 b'R' => [
878 0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
879 ],
880 b'S' => [
881 0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
882 ],
883 b'T' => [
884 0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
885 ],
886 b'U' => [
887 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
888 ],
889 b'V' => [
890 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
891 ],
892 b'W' => [
893 0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001,
894 ],
895 b'X' => [
896 0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
897 ],
898 b'Y' => [
899 0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
900 ],
901 b'Z' => [
902 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111,
903 ],
904 b'0' => [
905 0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
906 ],
907 b'1' => [
908 0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
909 ],
910 b'2' => [
911 0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
912 ],
913 b'3' => [
914 0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110,
915 ],
916 b'4' => [
917 0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
918 ],
919 b'5' => [
920 0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
921 ],
922 b'6' => [
923 0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
924 ],
925 b'7' => [
926 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
927 ],
928 b'8' => [
929 0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
930 ],
931 b'9' => [
932 0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
933 ],
934 b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
935 b',' => [0, 0, 0, 0, 0b01100, 0b01100, 0b01000],
936 b'!' => [
937 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100,
938 ],
939 b'?' => [
940 0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b00000, 0b00100,
941 ],
942 b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
943 b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
944 b';' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0b01000],
945 b'\'' => [0b00100, 0b00100, 0b01000, 0, 0, 0, 0],
946 b'"' => [0b01010, 0b01010, 0, 0, 0, 0, 0],
947 b'(' => [
948 0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010,
949 ],
950 b')' => [
951 0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000,
952 ],
953 b'/' => [
954 0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000,
955 ],
956 b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
957 b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
958 b'*' => [0, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0],
959 b'#' => [
960 0b01010, 0b01010, 0b11111, 0b01010, 0b11111, 0b01010, 0b01010,
961 ],
962 b'%' => [
963 0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011,
964 ],
965 b'&' => [
966 0b01100, 0b10010, 0b10100, 0b01000, 0b10101, 0b10010, 0b01101,
967 ],
968 _ => return None,
969 };
970 Some(rows)
971}
972
973struct OutlineBuilder {
975 units: f64,
976 contours: Vec<Vec<Point>>,
977 current: Vec<Point>,
978}
979
980impl OutlineBuilder {
981 fn new(units: f64) -> Self {
982 Self {
983 units,
984 contours: Vec::new(),
985 current: Vec::new(),
986 }
987 }
988
989 fn point(&self, x: f32, y: f32) -> Point {
990 Point::new(f64::from(x) / self.units, f64::from(y) / self.units)
991 }
992
993 fn finish_contour(&mut self) {
994 if self.current.len() > 1 {
995 self.contours.push(std::mem::take(&mut self.current));
996 }
997 }
998}
999
1000impl ttf_parser::OutlineBuilder for OutlineBuilder {
1001 fn move_to(&mut self, x: f32, y: f32) {
1002 self.finish_contour();
1003 self.current.push(self.point(x, y));
1004 }
1005
1006 fn line_to(&mut self, x: f32, y: f32) {
1007 self.current.push(self.point(x, y));
1008 }
1009
1010 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
1011 let Some(&start) = self.current.last() else {
1012 return;
1013 };
1014 let control = self.point(x1, y1);
1015 let end = self.point(x, y);
1016 for step in 1..=8 {
1017 let t = f64::from(step) / 8.0;
1018 let u = 1.0 - t;
1019 self.current.push(Point::new(
1020 u * u * start.x + 2.0 * u * t * control.x + t * t * end.x,
1021 u * u * start.y + 2.0 * u * t * control.y + t * t * end.y,
1022 ));
1023 }
1024 }
1025
1026 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
1027 let Some(&start) = self.current.last() else {
1028 return;
1029 };
1030 let c1 = self.point(x1, y1);
1031 let c2 = self.point(x2, y2);
1032 let end = self.point(x, y);
1033 for step in 1..=12 {
1034 let t = f64::from(step) / 12.0;
1035 let u = 1.0 - t;
1036 self.current.push(Point::new(
1037 u * u * u * start.x
1038 + 3.0 * u * u * t * c1.x
1039 + 3.0 * u * t * t * c2.x
1040 + t * t * t * end.x,
1041 u * u * u * start.y
1042 + 3.0 * u * u * t * c1.y
1043 + 3.0 * u * t * t * c2.y
1044 + t * t * t * end.y,
1045 ));
1046 }
1047 }
1048
1049 fn close(&mut self) {
1050 self.finish_contour();
1051 }
1052}
1053
1054#[cfg(test)]
1055mod tests {
1056 use super::Font;
1057 use pdf2::Encoding;
1058
1059 #[test]
1060 fn the_builtin_font_draws_letters_as_ink() {
1061 let font = Font::builtin(Encoding::standard());
1062 let glyph = font.glyph(b'H').expect("H");
1063 assert!(!glyph.contours.is_empty());
1064 assert!((glyph.advance - 0.6667).abs() < 1e-3);
1065 for contour in &glyph.contours {
1067 assert_eq!(contour.len(), 4);
1068 for point in contour {
1069 assert!(point.x >= 0.0 && point.x <= 6.0 / 9.0 + 1e-9);
1070 assert!(point.y >= 0.0 && point.y <= 7.0 / 9.0 + 1e-9);
1071 }
1072 }
1073 }
1074
1075 #[test]
1076 fn the_builtin_font_is_blank_for_space() {
1077 let font = Font::builtin(Encoding::standard());
1078 let glyph = font.glyph(b' ').expect("space");
1079 assert!(glyph.contours.is_empty());
1080 assert!(glyph.advance > 0.0);
1081 }
1082
1083 #[test]
1084 fn glyph_ids_are_selected_directly_for_composite_fonts() {
1085 let font = Font::builtin(Encoding::standard());
1086 assert!(
1087 font.glyph_by_id(1).is_none(),
1088 "the bitmap alphabet has no glyph ids"
1089 );
1090 }
1091
1092 #[test]
1093 fn a_broken_font_program_is_rejected() {
1094 assert!(Font::true_type(Encoding::standard(), vec![0, 1, 2, 3]).is_none());
1095 assert!(Font::true_type(Encoding::standard(), Vec::new()).is_none());
1096 }
1097
1098 #[test]
1099 fn accented_latin_composes_instead_of_drawing_notdef() {
1100 let font = Font::builtin(Encoding::win_ansi());
1101 for (code, base, marks) in [
1104 (0xE9_u8, b'E', 3), (0xF1, b'N', 3), (0xFC, b'U', 2), (0xE7, b'C', 3), (0xE5, b'A', 4), (0xE2, b'A', 3), ] {
1111 let glyph = font.glyph(code).expect("a composed glyph");
1112 let plain = font.glyph(base).expect("the base letter");
1113 assert_eq!(
1114 glyph.contours.len(),
1115 plain.contours.len() + marks,
1116 "{} on {}",
1117 code as char,
1118 base as char
1119 );
1120 assert_ne!(glyph.contours, plain.contours);
1121 }
1122 let other = font.glyph(0xA4).expect("undefined code");
1125 assert_eq!(other.contours.len(), 20, "the notdef box");
1126 }
1127
1128 #[test]
1129 fn marks_sit_outside_the_glyph_box_and_cedillas_below_the_baseline() {
1130 let font = Font::builtin(Encoding::win_ansi());
1131 let acute = font.glyph(0xE9).expect("é");
1132 let top = acute
1133 .contours
1134 .iter()
1135 .flatten()
1136 .fold(f64::MIN, |max, point| max.max(point.y));
1137 assert!((7.0 / 9.0..=1.0).contains(&top), "accent tops out at {top}");
1138 let cedilla = font.glyph(0xE7).expect("ç");
1139 let bottom = cedilla
1140 .contours
1141 .iter()
1142 .flatten()
1143 .fold(f64::MAX, |min, point| min.min(point.y));
1144 assert!(bottom < 0.0, "the cedilla hangs to {bottom}");
1145 }
1146
1147 #[test]
1148 fn unknown_characters_become_the_notdef_box() {
1149 let font = Font::builtin(Encoding::standard());
1150 assert!(font.glyph(0xA4).is_none());
1152 let glyph = font.glyph(b'@').expect("@");
1154 assert_eq!(
1155 glyph.contours.len(),
1156 20,
1157 "the notdef box is a hollow 5×7 frame"
1158 );
1159 }
1160}
1161
1162#[cfg(test)]
1163mod cff_tests {
1164 use super::{cff_layout, top_dict_operator, wrap_cff, Font};
1165
1166 fn synthetic_cff() -> Vec<u8> {
1170 let mut cff = vec![1, 0, 4, 4];
1171 cff.extend_from_slice(&[0, 1, 1, 1, 2, b'A']);
1173 cff.extend_from_slice(&[0, 1, 1, 1, 7]);
1175 cff.extend_from_slice(&[29, 0, 0, 0, 25, 17]);
1176 cff.extend_from_slice(&[0, 0]);
1178 cff.extend_from_slice(&[0, 0]);
1179 assert_eq!(cff.len(), 25, "the CharStrings offset above");
1180 cff.extend_from_slice(&[0, 3, 1, 1, 1, 1, 1]);
1182 cff
1183 }
1184
1185 #[test]
1186 fn a_bare_cff_becomes_a_face_ttf_parser_reads() {
1187 let cff = synthetic_cff();
1188 let (charset_at, glyphs) = cff_layout(&cff).expect("layout");
1189 assert_eq!((charset_at, glyphs), (0, 3), "predefined charset, 3 glyphs");
1190 let wrapped = wrap_cff(&cff, glyphs).expect("wrap");
1191 let face = ttf_parser::Face::parse(&wrapped, 0).expect("parse the wrapper");
1192 assert_eq!(face.number_of_glyphs(), 3);
1193 assert_eq!(face.units_per_em(), 1000);
1194 assert!(Font::cff(pdf2::Encoding::standard(), cff).is_some());
1195 }
1196
1197 #[test]
1198 fn a_program_without_charstrings_is_refused() {
1199 let cff = synthetic_cff();
1201 assert!(cff_layout(&cff[..8]).is_none());
1202 assert!(Font::cff(pdf2::Encoding::standard(), vec![0, 1]).is_none());
1203 }
1204
1205 #[test]
1206 fn the_top_dict_operator_reader_handles_each_number_encoding() {
1207 assert_eq!(top_dict_operator(&[29, 0, 0, 1, 0, 17], 17), Some(256));
1209 assert_eq!(top_dict_operator(&[28, 1, 0, 17], 17), Some(256));
1210 assert_eq!(top_dict_operator(&[139 + 42, 17], 17), Some(42));
1211 assert_eq!(top_dict_operator(&[251, 0, 17], 17), None);
1213 assert_eq!(
1214 top_dict_operator(&[29, 0, 0, 0, 9], 17),
1215 None,
1216 "no operator"
1217 );
1218 }
1219}
1220
1221#[cfg(test)]
1222mod cache_tests {
1223 use super::Font;
1224 use pdf2::Encoding;
1225
1226 fn subset_font() -> Vec<u8> {
1227 std::fs::read(concat!(
1228 env!("CARGO_MANIFEST_DIR"),
1229 "/../../tests/fixtures/fonts/CrimsonText-Regular-subset.ttf"
1230 ))
1231 .expect("the committed subset font")
1232 }
1233
1234 #[test]
1235 fn a_glyph_looked_up_twice_is_the_same_outline() {
1236 let font = Font::true_type(Encoding::standard(), subset_font()).expect("font");
1237 let first = font.glyph(b'A').expect("A");
1238 let second = font.glyph(b'A').expect("A");
1239 assert_eq!(first, second, "the cache returns what the parser did");
1240 assert!(!first.contours.is_empty(), "A is a drawn glyph");
1241 assert!(first.advance > 0.0);
1242 let b = font.glyph(b'B').expect("B");
1244 assert_ne!(first, b);
1245 }
1246
1247 #[test]
1248 fn the_cache_is_shared_by_clones_and_survives_them() {
1249 let font = Font::true_type(Encoding::standard(), subset_font()).expect("font");
1250 let clone = font.clone();
1251 let from_original = font.glyph(b'C').expect("C");
1252 let from_clone = clone.glyph(b'C').expect("C");
1253 assert_eq!(from_original, from_clone);
1254 }
1255
1256 #[test]
1257 fn a_program_with_a_cmap_answers_the_question_honestly() {
1258 let with_cmap = Font::true_type(Encoding::standard(), subset_font()).expect("font");
1259 assert!(with_cmap.has_character_map());
1260 assert!(with_cmap.glyph(b'Z').is_some(), "the subset carries Z");
1261 assert!(
1262 with_cmap.glyph(0x00).is_none(),
1263 "an unmapped code has no glyph"
1264 );
1265 }
1266}