1use pdf2::Encoding;
5
6use crate::geom::Point;
7
8#[derive(Debug, Clone, Default, PartialEq)]
11pub struct Glyph {
12 pub contours: Vec<Vec<Point>>,
14 pub advance: f64,
16}
17
18#[derive(Debug, Clone)]
20pub enum Font {
21 Builtin {
24 encoding: Encoding,
26 },
27 TrueType {
29 encoding: Encoding,
31 data: Vec<u8>,
34 },
35}
36
37impl Font {
38 pub fn builtin(encoding: Encoding) -> Self {
40 Self::Builtin { encoding }
41 }
42
43 pub fn true_type(encoding: Encoding, data: Vec<u8>) -> Option<Self> {
45 let face = ttf_parser::Face::parse(&data, 0).ok()?;
46 if face.units_per_em() == 0 {
47 return None;
48 }
49 Some(Self::TrueType { encoding, data })
50 }
51
52 pub fn glyph(&self, code: u8) -> Option<Glyph> {
55 match self {
56 Self::Builtin { encoding } => builtin_glyph(encoding.character(code)?),
57 Self::TrueType { encoding, data } => {
58 let character = encoding.character(code)?;
59 let face = ttf_parser::Face::parse(data, 0).ok()?;
60 let glyph_id = face.glyph_index(character)?;
61 glyph_from_face(data, glyph_id)
62 }
63 }
64 }
65
66 pub fn advance(&self, code: u8) -> f64 {
68 self.glyph(code)
69 .map_or(BUILTIN_ADVANCE, |glyph| glyph.advance)
70 }
71
72 pub fn glyph_by_id(&self, id: u16) -> Option<Glyph> {
77 match self {
78 Self::Builtin { .. } => None,
79 Self::TrueType { data, .. } => glyph_from_face(data, ttf_parser::GlyphId(id)),
80 }
81 }
82}
83
84fn glyph_from_face(data: &[u8], glyph_id: ttf_parser::GlyphId) -> Option<Glyph> {
86 let face = ttf_parser::Face::parse(data, 0).ok()?;
87 let units = f64::from(face.units_per_em());
88 let mut builder = OutlineBuilder::new(units);
89 face.outline_glyph(glyph_id, &mut builder)?;
90 let advance = f64::from(face.glyph_hor_advance(glyph_id).unwrap_or(0)) / units;
91 Some(Glyph {
92 contours: builder.contours,
93 advance,
94 })
95}
96
97const BUILTIN_ADVANCE: f64 = 6.0 / 9.0;
98const BUILTIN_CELL: f64 = 1.0 / 9.0;
99const BUILTIN_WIDTH: u8 = 5;
100const BUILTIN_HEIGHT: u8 = 7;
101
102fn builtin_glyph(character: char) -> Option<Glyph> {
105 let code = u8::try_from(u32::from(character)).ok()?;
106 if character == ' ' {
107 return Some(Glyph {
108 contours: Vec::new(),
109 advance: BUILTIN_ADVANCE,
110 });
111 }
112 if let Some(rows) = glyph_rows(code) {
113 return Some(Glyph {
114 contours: rows_to_contours(&rows),
115 advance: BUILTIN_ADVANCE,
116 });
117 }
118 if character == '\u{2022}' {
119 return Some(Glyph {
120 contours: rows_to_contours(&[0, 0, 0b00100, 0b01110, 0b00100, 0, 0]),
121 advance: BUILTIN_ADVANCE,
122 });
123 }
124 if let Some((base, accent)) = decompose(character) {
127 let rows = glyph_rows(u8::try_from(u32::from(base)).unwrap_or(b'?'))
128 .or_else(|| upper(base).and_then(|upper| glyph_rows(upper as u8)))
129 .unwrap_or_else(notdef_rows);
130 let mut contours = rows_to_contours(&rows);
131 contours.extend(
132 accent
133 .cells()
134 .iter()
135 .map(|&(column, layer)| mark_cell(column, layer)),
136 );
137 return Some(Glyph {
138 contours,
139 advance: BUILTIN_ADVANCE,
140 });
141 }
142 if character == '\u{00F8}' || character == '\u{00D8}' {
143 let mut contours = rows_to_contours(&glyph_rows(b'O').unwrap_or_else(notdef_rows));
146 contours.extend(
147 [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)]
148 .iter()
149 .map(|&(column, layer)| mark_cell(column, layer)),
150 );
151 return Some(Glyph {
152 contours,
153 advance: BUILTIN_ADVANCE,
154 });
155 }
156 let rows = upper(character)
157 .and_then(|upper| glyph_rows(upper as u8))
158 .unwrap_or_else(notdef_rows);
159 Some(Glyph {
160 contours: rows_to_contours(&rows),
161 advance: BUILTIN_ADVANCE,
162 })
163}
164
165#[derive(Clone, Copy, PartialEq, Eq, Debug)]
168enum Accent {
169 Acute,
170 Grave,
171 Circumflex,
172 Diaeresis,
173 Tilde,
174 Ring,
175 Cedilla,
176}
177
178impl Accent {
179 fn cells(self) -> &'static [(u8, i8)] {
183 match self {
184 Self::Acute => &[(2, 0), (3, 0), (3, 1)],
185 Self::Grave => &[(2, 1), (3, 1), (3, 0)],
186 Self::Circumflex => &[(1, 0), (2, 1), (3, 0)],
187 Self::Diaeresis => &[(1, 1), (3, 1)],
188 Self::Tilde => &[(1, 1), (2, 0), (3, 1)],
189 Self::Ring => &[(1, 0), (2, 1), (3, 0), (2, 0)],
190 Self::Cedilla => &[(2, -1), (3, -1), (3, -2)],
191 }
192 }
193}
194
195fn mark_cell(column: u8, layer: i8) -> Vec<Point> {
197 let x0 = f64::from(column) * BUILTIN_CELL;
198 let x1 = x0 + BUILTIN_CELL;
199 let (bottom, top) = if layer < 0 {
200 (
201 f64::from(layer) * BUILTIN_CELL,
202 f64::from(layer + 1) * BUILTIN_CELL,
203 )
204 } else {
205 (
206 f64::from(BUILTIN_HEIGHT + layer as u8) * BUILTIN_CELL,
207 f64::from(BUILTIN_HEIGHT + layer as u8 + 1) * BUILTIN_CELL,
208 )
209 };
210 vec![
211 Point::new(x0, bottom),
212 Point::new(x1, bottom),
213 Point::new(x1, top),
214 Point::new(x0, top),
215 ]
216}
217
218fn decompose(character: char) -> Option<(char, Accent)> {
221 let (base, accent) = match character {
222 'á' | 'Á' => ('a', Accent::Acute),
223 'é' | 'É' => ('e', Accent::Acute),
224 'í' | 'Í' => ('i', Accent::Acute),
225 'ó' | 'Ó' => ('o', Accent::Acute),
226 'ú' | 'Ú' => ('u', Accent::Acute),
227 'ý' | 'Ý' => ('y', Accent::Acute),
228 'à' | 'À' => ('a', Accent::Grave),
229 'è' | 'È' => ('e', Accent::Grave),
230 'ì' | 'Ì' => ('i', Accent::Grave),
231 'ò' | 'Ò' => ('o', Accent::Grave),
232 'ù' | 'Ù' => ('u', Accent::Grave),
233 'â' | 'Â' => ('a', Accent::Circumflex),
234 'ê' | 'Ê' => ('e', Accent::Circumflex),
235 'î' | 'Î' => ('i', Accent::Circumflex),
236 'ô' | 'Ô' => ('o', Accent::Circumflex),
237 'û' | 'Û' => ('u', Accent::Circumflex),
238 'ä' | 'Ä' => ('a', Accent::Diaeresis),
239 'ë' | 'Ë' => ('e', Accent::Diaeresis),
240 'ï' | 'Ï' => ('i', Accent::Diaeresis),
241 'ö' | 'Ö' => ('o', Accent::Diaeresis),
242 'ü' | 'Ü' => ('u', Accent::Diaeresis),
243 'ÿ' | 'Ÿ' => ('y', Accent::Diaeresis),
244 'ã' | 'Ã' => ('a', Accent::Tilde),
245 'õ' | 'Õ' => ('o', Accent::Tilde),
246 'ñ' | 'Ñ' => ('n', Accent::Tilde),
247 'å' | 'Å' => ('a', Accent::Ring),
248 'ç' | 'Ç' => ('c', Accent::Cedilla),
249 _ => return None,
250 };
251 Some((base, accent))
252}
253
254fn upper(character: char) -> Option<char> {
255 character
256 .to_uppercase()
257 .next()
258 .filter(|upper| *upper != character)
259}
260
261fn notdef_rows() -> [u8; BUILTIN_HEIGHT as usize] {
262 [
263 0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111,
264 ]
265}
266
267fn rows_to_contours(rows: &[u8; BUILTIN_HEIGHT as usize]) -> Vec<Vec<Point>> {
268 let mut contours = Vec::new();
269 for (row, bits) in rows.iter().enumerate() {
270 for column in 0..BUILTIN_WIDTH {
271 let mask = 1_u8 << (BUILTIN_WIDTH - 1 - column);
272 if bits & mask == 0 {
273 continue;
274 }
275 let x0 = f64::from(column) * BUILTIN_CELL;
276 let x1 = x0 + BUILTIN_CELL;
277 let top = f64::from(BUILTIN_HEIGHT - 1 - row as u8) * BUILTIN_CELL;
278 let bottom = top + BUILTIN_CELL;
279 contours.push(vec![
280 Point::new(x0, bottom),
281 Point::new(x1, bottom),
282 Point::new(x1, top),
283 Point::new(x0, top),
284 ]);
285 }
286 }
287 contours
288}
289
290fn glyph_rows(code: u8) -> Option<[u8; 7]> {
291 let rows = match code {
292 b'A' => [
293 0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
294 ],
295 b'B' => [
296 0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110,
297 ],
298 b'C' => [
299 0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
300 ],
301 b'D' => [
302 0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
303 ],
304 b'E' => [
305 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
306 ],
307 b'F' => [
308 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000,
309 ],
310 b'G' => [
311 0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110,
312 ],
313 b'H' => [
314 0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
315 ],
316 b'I' => [
317 0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
318 ],
319 b'J' => [
320 0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100,
321 ],
322 b'K' => [
323 0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001,
324 ],
325 b'L' => [
326 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
327 ],
328 b'M' => [
329 0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
330 ],
331 b'N' => [
332 0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
333 ],
334 b'O' => [
335 0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
336 ],
337 b'P' => [
338 0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
339 ],
340 b'Q' => [
341 0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101,
342 ],
343 b'R' => [
344 0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
345 ],
346 b'S' => [
347 0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
348 ],
349 b'T' => [
350 0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
351 ],
352 b'U' => [
353 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
354 ],
355 b'V' => [
356 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
357 ],
358 b'W' => [
359 0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001,
360 ],
361 b'X' => [
362 0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
363 ],
364 b'Y' => [
365 0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
366 ],
367 b'Z' => [
368 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111,
369 ],
370 b'0' => [
371 0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
372 ],
373 b'1' => [
374 0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
375 ],
376 b'2' => [
377 0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
378 ],
379 b'3' => [
380 0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110,
381 ],
382 b'4' => [
383 0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
384 ],
385 b'5' => [
386 0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
387 ],
388 b'6' => [
389 0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
390 ],
391 b'7' => [
392 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
393 ],
394 b'8' => [
395 0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
396 ],
397 b'9' => [
398 0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
399 ],
400 b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
401 b',' => [0, 0, 0, 0, 0b01100, 0b01100, 0b01000],
402 b'!' => [
403 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100,
404 ],
405 b'?' => [
406 0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b00000, 0b00100,
407 ],
408 b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
409 b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
410 b';' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0b01000],
411 b'\'' => [0b00100, 0b00100, 0b01000, 0, 0, 0, 0],
412 b'"' => [0b01010, 0b01010, 0, 0, 0, 0, 0],
413 b'(' => [
414 0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010,
415 ],
416 b')' => [
417 0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000,
418 ],
419 b'/' => [
420 0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000,
421 ],
422 b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
423 b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
424 b'*' => [0, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0],
425 b'#' => [
426 0b01010, 0b01010, 0b11111, 0b01010, 0b11111, 0b01010, 0b01010,
427 ],
428 b'%' => [
429 0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011,
430 ],
431 b'&' => [
432 0b01100, 0b10010, 0b10100, 0b01000, 0b10101, 0b10010, 0b01101,
433 ],
434 _ => return None,
435 };
436 Some(rows)
437}
438
439struct OutlineBuilder {
441 units: f64,
442 contours: Vec<Vec<Point>>,
443 current: Vec<Point>,
444}
445
446impl OutlineBuilder {
447 fn new(units: f64) -> Self {
448 Self {
449 units,
450 contours: Vec::new(),
451 current: Vec::new(),
452 }
453 }
454
455 fn point(&self, x: f32, y: f32) -> Point {
456 Point::new(f64::from(x) / self.units, f64::from(y) / self.units)
457 }
458
459 fn finish_contour(&mut self) {
460 if self.current.len() > 1 {
461 self.contours.push(std::mem::take(&mut self.current));
462 }
463 }
464}
465
466impl ttf_parser::OutlineBuilder for OutlineBuilder {
467 fn move_to(&mut self, x: f32, y: f32) {
468 self.finish_contour();
469 self.current.push(self.point(x, y));
470 }
471
472 fn line_to(&mut self, x: f32, y: f32) {
473 self.current.push(self.point(x, y));
474 }
475
476 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
477 let Some(&start) = self.current.last() else {
478 return;
479 };
480 let control = self.point(x1, y1);
481 let end = self.point(x, y);
482 for step in 1..=8 {
483 let t = f64::from(step) / 8.0;
484 let u = 1.0 - t;
485 self.current.push(Point::new(
486 u * u * start.x + 2.0 * u * t * control.x + t * t * end.x,
487 u * u * start.y + 2.0 * u * t * control.y + t * t * end.y,
488 ));
489 }
490 }
491
492 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
493 let Some(&start) = self.current.last() else {
494 return;
495 };
496 let c1 = self.point(x1, y1);
497 let c2 = self.point(x2, y2);
498 let end = self.point(x, y);
499 for step in 1..=12 {
500 let t = f64::from(step) / 12.0;
501 let u = 1.0 - t;
502 self.current.push(Point::new(
503 u * u * u * start.x
504 + 3.0 * u * u * t * c1.x
505 + 3.0 * u * t * t * c2.x
506 + t * t * t * end.x,
507 u * u * u * start.y
508 + 3.0 * u * u * t * c1.y
509 + 3.0 * u * t * t * c2.y
510 + t * t * t * end.y,
511 ));
512 }
513 }
514
515 fn close(&mut self) {
516 self.finish_contour();
517 }
518}
519
520#[cfg(test)]
521mod tests {
522 use super::Font;
523 use pdf2::Encoding;
524
525 #[test]
526 fn the_builtin_font_draws_letters_as_ink() {
527 let font = Font::builtin(Encoding::standard());
528 let glyph = font.glyph(b'H').expect("H");
529 assert!(!glyph.contours.is_empty());
530 assert!((glyph.advance - 0.6667).abs() < 1e-3);
531 for contour in &glyph.contours {
533 assert_eq!(contour.len(), 4);
534 for point in contour {
535 assert!(point.x >= 0.0 && point.x <= 6.0 / 9.0 + 1e-9);
536 assert!(point.y >= 0.0 && point.y <= 7.0 / 9.0 + 1e-9);
537 }
538 }
539 }
540
541 #[test]
542 fn the_builtin_font_is_blank_for_space() {
543 let font = Font::builtin(Encoding::standard());
544 let glyph = font.glyph(b' ').expect("space");
545 assert!(glyph.contours.is_empty());
546 assert!(glyph.advance > 0.0);
547 }
548
549 #[test]
550 fn glyph_ids_are_selected_directly_for_composite_fonts() {
551 let font = Font::builtin(Encoding::standard());
552 assert!(
553 font.glyph_by_id(1).is_none(),
554 "the bitmap alphabet has no glyph ids"
555 );
556 }
557
558 #[test]
559 fn a_broken_font_program_is_rejected() {
560 assert!(Font::true_type(Encoding::standard(), vec![0, 1, 2, 3]).is_none());
561 assert!(Font::true_type(Encoding::standard(), Vec::new()).is_none());
562 }
563
564 #[test]
565 fn accented_latin_composes_instead_of_drawing_notdef() {
566 let font = Font::builtin(Encoding::win_ansi());
567 for (code, base, marks) in [
570 (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), ] {
577 let glyph = font.glyph(code).expect("a composed glyph");
578 let plain = font.glyph(base).expect("the base letter");
579 assert_eq!(
580 glyph.contours.len(),
581 plain.contours.len() + marks,
582 "{} on {}",
583 code as char,
584 base as char
585 );
586 assert_ne!(glyph.contours, plain.contours);
587 }
588 let other = font.glyph(0xA4).expect("undefined code");
591 assert_eq!(other.contours.len(), 20, "the notdef box");
592 }
593
594 #[test]
595 fn marks_sit_outside_the_glyph_box_and_cedillas_below_the_baseline() {
596 let font = Font::builtin(Encoding::win_ansi());
597 let acute = font.glyph(0xE9).expect("é");
598 let top = acute
599 .contours
600 .iter()
601 .flatten()
602 .fold(f64::MIN, |max, point| max.max(point.y));
603 assert!((7.0 / 9.0..=1.0).contains(&top), "accent tops out at {top}");
604 let cedilla = font.glyph(0xE7).expect("ç");
605 let bottom = cedilla
606 .contours
607 .iter()
608 .flatten()
609 .fold(f64::MAX, |min, point| min.min(point.y));
610 assert!(bottom < 0.0, "the cedilla hangs to {bottom}");
611 }
612
613 #[test]
614 fn unknown_characters_become_the_notdef_box() {
615 let font = Font::builtin(Encoding::standard());
616 assert!(font.glyph(0xA4).is_none());
618 let glyph = font.glyph(b'@').expect("@");
620 assert_eq!(
621 glyph.contours.len(),
622 20,
623 "the notdef box is a hollow 5×7 frame"
624 );
625 }
626}